Multi-client Icons: Macbook Pro – jasonrm, Server – visualpharm.

Handling multiple clients in Java is relatively easy and painless compared to C for example. This is because Java hides a lot of the complexities of writing your application to make use of multiple threads. Basically all that needs to be written is a class, ClientHandler say, the implements Runnable and handles the client. ClientHandler‘s constructor takes the client Socket as an input, so that it has something to act upon. And, the run() method does whatever needs to be done (i.e. reading and writing to the Socket) and then close()s the Socket. ClientHandler Implementation
package uk.co.hejp.Server;

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

public class ClientHandler implements Runnable {
	Socket socket;
	PrintStream out;

	ClientHandler(Socket s) {
		socket = s;
	}

	@Override
	public void run() {

		try {
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			System.out.println("PrintStream Error");
		}

		out.println("Hello");

		try {
			socket.close();
		} catch (IOException e) {
			System.out.println("Failed to close, oddly...");
		}
	}

}
This particular implementation of ClientHandler just writes ‘Hello’ to the Socket and close()s. And just for completeness here is an implementation of a Server that uses ClientHandler:
package uk.co.hejp.Server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	static ServerSocket socket;
	static int port = 7999;

	public static void main(String[] args) {

		try {
			socket = new ServerSocket(port);
			System.out.println("Bound to port: " + port);
		} catch (IOException e) {
			System.out.println("Cannot bind to port: " + port);
			System.exit(0);
		}

		while (true) {
			try {
				Socket s = socket.accept();
				System.out.println("New Client: "+s.getInetAddress().toString());
				(new Thread(new ClientHandler(s))).start();
			} catch (IOException e) {
				System.out.println("Failed to accept client");
			}
		}

	}
}
To test this Server you can use telnet (telnet 127.0.0.1 7999) or in your favourite browser goto ‘http://localhost:7999/’ the result should be just a line to text ‘Hello’ assuming you have the Server running.

89 Responses to “Java Socket Programming, Handling Multiple Clients”

  1. adidas Says:

    its good but not so good

    [Reply]

  2. mrutyunjay sawant Says:

    thanx…..

    [Reply]

  3. our web site Says:

    Heya! I’m at work surfing around your blog from my new iphone 4! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the outstanding work!

    [Reply]

  4. where does bed bugs originate from Says:

    You’re so awesome! I don’t suppose I’ve read through anything like that before. So wonderful to find another person with some unique thoughts on this topic. Really.. many thanks for starting this up. This site is something that’s needed on the internet, someone
    with a bit of originality!

    Have a look at my web blog where does bed bugs originate from

    [Reply]

  5. white christmas Says:

    Hello, I want to subscribe for this website to take most recent updates,
    so where can i do it please help.

    Also visit my web page: white christmas

    [Reply]

  6. autocom Says:

    Wow! It is also nice article about JavaScript, I am genuinely eager of learning JavaScript. thanks admin

    [Reply]

  7. kredyty bez bik tarnów Says:

    Hi there! I simply want to offer you a big thumbs
    up for the excellent information you have right here on this post.
    I am returning to your blog for more soon.

    Review my web site: kredyty bez bik tarnów

    [Reply]

  8. tablets youtube Says:

    I am genuinely glad to glance at this webpage posts which carries lots of
    valuable data, thanks for providing these information.

    [Reply]

  9. kredyt przez internet Says:

    We’re a gaggle of volunteers and beginning a new design in your local community. Your web site available you together with very helpful info to work upon. You will have completed an outstanding pastime and also our own complete local community would be fortunate to you personally.

    [Reply]

  10. akshay Says:

    Nice program for newbie of socket programming. Thanks

    [Reply]

  11. cpe3a Says:

    hi, what if i have 3 clients connected to the server, how can i read and write only to a specific client/only two clients?

    [Reply]

  12. Cameron Says:

    hi!,I like your writing very a lot! proportion we be in contact more about your post on AOL?
    I require an expert in this area to resolve my problem. Maybe that is you!
    Taking a look forward to see you.

    [Reply]

  13. seo Says:

    Just wish to say your article is as astounding.
    The clearness in your post is simply cool and i could
    assume you’re an expert on this subject. Well with your permission allow me to grab your feed
    to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.

    [Reply]

  14. Esther Frankel Says:

    Way cool! Some very valid points! I appreciate you writing this write-up plus the rest of the site is very good.

    [Reply]

  15. Anonymous Says:

    My developer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs.

    But he’s tryiong none the less. I’ve been using Movable-type on various websites for about a year and am anxious about switching
    to another platform. I have heard fantastic things about blogengine.net.
    Is there a way I can transfer all my wordpress posts into it?
    Any kind of help would be greatly appreciated!

    [Reply]

  16. God Of War Download Says:

    hello!,I love your writing so a lot! proportion we keep up a correspondence extra approximately
    your post on AOL? I need an expert on this area to solve my problem.

    May be that’s you! Taking a look ahead to see you.

    [Reply]

  17. how to make your penis grow faster Says:

    What’s up to every one, it’s really a pleasant for me to go to see this site, it
    includes valuable Information.

    [Reply]

  18. Stop the Dolphin Slaughter Says:

    Hello! This is kind of off topic but I need some help from an
    established blog. Is it tough to set up your own blog? I’m not very techincal
    but I can figure things out pretty quick. I’m thinking about
    creating my own but I’m not sure where to begin. Do you have any
    points or suggestions? With thanks

    Here is my website – Stop the Dolphin Slaughter

    [Reply]

  19. wordpress deveolper Says:

    Word – Press also give its user a benefit to create
    any look that they want. The most noteworthy things
    about a web portal powered with Word – Press is that it comes with an intelligent text formatting feature along with cross-browser
    bookmarklets, highly advanced user system, easy installation and upgrades, protected password posts, full W3C standards compliance, cross-blog communication tools and so on.
    The web development industry constantly shifting towards PSD to
    Word – Press conversion.

    [Reply]

  20. document management software Says:

    Gone are the days when office clerks would spend hours
    bent over their desks, copying out important documents by
    hand. This feature can make it a lot easier to go through the
    different version of a document just in case they are needed for future use.
    Similarly, the capture of a grievance form from an employee
    could trigger a procedure to send that grievance forward to the human resources department and to the appropriate members of the management team.

    Feel free to surf to my web-site :: document management software

    [Reply]

  21. projektowanie stron www moji poznanici pozivnica Says:

    ?achwycaj?cag??bia:-D

    [Reply]

  22. business listing Says:

    I’m not sure exactly why but this web site is loading incredibly slow for me.
    Is anyone else having this problem or is it a issue on my end?

    I’ll check back later and see if the problem still exists.

    [Reply]

  23. terrazzo tile Says:

    Fantastic items from you, man. I’ve have in mind
    your stuff previous to and you are just extremely great.
    I really like what you’ve bought here, certainly like what you’re
    stating and the way in which wherein you are saying it.
    You make it entertaining and you still take care of
    to stay it smart. I can not wait to learn far more from you.
    That is really a wonderful website.

    [Reply]

  24. New Townhouses American College Theme Parks DC Says:

    Great blog here! Also your web site so much up fast!
    What web host are you using? Can I am getting your associate link on your host?
    I wish my website loaded up as quickly as yours lol

    [Reply]

  25. Hatteras Charter Fishing Boats Says:

    Hi, its good paragraph concerning media print, we all be aware of
    media is a fantastic source of information.

    Feel free to surf to my homepage :: Hatteras Charter Fishing Boats

    [Reply]

  26. Luciana Says:

    What’s up to every body, it’s my first go to see of this web site; this weblog
    contains awesome and in fact good data for readers.

    [Reply]

  27. Pilat Says:

    If some one desires to be updated with newest technologies after that he must be visit this website and be up to date every day.

    [Reply]

  28. Mobile Casino Instant No Deposit Bonus Says:

    Can I simply say what a comfort to find an individual who really understands what they are discussing on the net.
    You certainly realize how to bring a problem to light and make it important.
    More and more people have to check this out and understand this
    side of the story. It’s surprising you aren’t more popular because you
    most certainly possess the gift.

    [Reply]

  29. adoptar perros madrid cachorros Says:

    De ellos, ocho eran menores de un par de años.
    Certificado de residencia en Marruecos durante el proceso.

    [Reply]

  30. csr racing download Says:

    Hi, after reading this amazing paragraph i am too happy to share my know-how here with mates.

    [Reply]

  31. femme en dessous sexy Says:

    hello!,I really like your writing very much! share we be in contact more about your post on AOL?

    I require an expert in this house to resolve my problem.
    Maybe that’s you! Looking ahead to see you.

    [Reply]

  32. wordpress.com Says:

    Experimnentera med andra kåt? tjejer, prova
    på nya sexställningar, känn kicken aav hur spännande det är att ?a
    sex med en kåt tjej du precis har träffat.
    Upptäck njutningen aav att se din partner ?n action, alltså knulla medd
    någon annan, ddu kommer fnna dig själv få denn ultimata kickesn av erotisk njutning när ?u ser din partner
    bli knullad av ?n främling. När ?u har gjort
    ditt val registrerar ?u dig, loggar in, och väljer vilka av ?em tusentals bögar ?u vill prata
    med som finns registrerade på svenska dejtingsidor.

    [Reply]

  33. cell phone spy reviews blackberry Says:

    Its not my first time to visit this web site, i am visiting
    this site dailly aand obtain nice information from here everyday.

    [Reply]

  34. Rychle Rande Says:

    Seznamka vám ve dne i v noci nabízí na naší platform? možnostzapojit se ?? erotické?o chatu
    s registrovanými ?leny, nebo ?i rovnou domluvit sch?zku.
    Erotické chaty jsou dobrým zpusobem, jaak se s nekým blíž? seznámit pred samotným free sexem
    – mužete se bavit ? cem chcete, vést erotické rozhovory ? mužete dokonce
    i použít webcameru, abyte se ujistili, ž? opravdu erotické chaty vedete se sexy clovekem
    dle své?o gusta. nebo sse t?eba sejdete rovnou s
    n?kolika, pokud se na t? cítíte.

    [Reply]

  35. Picture Window Installation Cleveland Ohio Says:

    The benefits of Softwood Casement Windows

    There are numerous different Picture Window Installation Cleveland Ohio possibilities, whether you’re in the process of creating a brand new home otherwise you need windows for your existing home.
    Besides different styles, like casement windows, double hung
    and sash, but there are also lots of materials from hard or soft wood to
    PVC, aluminium plus more.

    [Reply]

  36. camquebec.blogspot.ro Says:

    Often we hear experts in the news that report a specific stock is gonna soar and now will be the time to purchase.
    So unless service repair shop completes the formalities and acquire the
    necessary certifications they could’t start their business.
    Donnie Jonston could be the author of this article about how you can make funds on Ebay Donnie has many years
    of work experience as being a writer as well as working with drop shippers in the variety of entrepreneurial ventures.

    My web page :: camquebec.blogspot.ro

    [Reply]

  37. cw.cx Says:

    Hi, always i used to check web site posts here in the early hours in the
    daylight, as i enjoy to gain knowledge of more and more.

    my blog – buy Ketone Slim XT – cw.cx -

    [Reply]

  38. les option binaire Says:

    I was recommended this web site by my cousin. I’m not sure whether this post
    is written by him as no one else know such detailed about my difficulty.

    You are amazing! Thanks!

    [Reply]

  39. larryjordan.biz ripple training final cut pro x Says:

    Hi there, just became aware of your blog through Google, and found that it is
    really informative. I am going to watch out for brussels.
    I’ll be grateful if you continue this in future. Lots of people will be benefited from your writing.
    Cheers!

    [Reply]

  40. tap Says:

    Terrific post however I was wanting to know if you could write a litte more on this topic?
    I’d be very thankful if you could elaborate a little bit further.

    Thank you!

    [Reply]

  41. Angry Birds epic hack Says:

    Excellent website you have here but I was wondering if you knew of any discussion boards that
    cover the same topics talked about here? I’d really love to be
    a part of community where I can get comments from other experienced people that share the
    same interest. If you have any suggestions, please let me know.
    Cheers!

    [Reply]

  42. the sims freeplay android Says:

    If some one wants expert view on tthe topic of bloggving after that i recommend him/her
    to pay a visit this web site, Keep up the nice work.

    [Reply]

  43. Transformers Age of Extinction Cheats Says:

    Good response in return of this query with solid arguments and
    telling the whole thing about that.

    [Reply]

  44. casablanca fans Says:

    If you desire to grow your knowledge simply keep visiting this web page and be updated with the hottest gossip posted here.

    [Reply]

  45. peso ideal Says:

    Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I acquire in fact enjoyed
    account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.

    [Reply]

  46. Quotes Says:

    It’s not my first time to pay a quick visit
    this site, i am visiting this web site dailly and obtain pleasant data
    from here all the time.

    my page – Quotes

    [Reply]

  47. Samba Télécharger Says:

    Thanks for sharing your thoughts about Samba Télécharger en français
    complet. Regards

    [Reply]

  48. g3nx.com Says:

    I comment whenever I especially enjoy a article on a website or I have something to valuable to contribute to the discussion. Usually
    it is caused by the sincerness communicated in the post I browsed.
    And after this post HEJP’s Blog ? Blog Archive ? Java Socket Programming, Handling Multiple Clients.
    I was actually moved enough to drop a thought :-P I actually do have a few questions for you if it’s allright.
    Could it be just me or do some of the responses look like they are
    coming from brain dead folks? :-P And, if you are posting on other social sites, I’d like
    to follow anything new you have to post. Could you make a list the
    complete urls of your communal pages like your twitter feed, Facebook page or linkedin profile?

    [Reply]

  49. cool bongs Says:

    If you are unsure here are some signs of possible drug use:
    . Begin as early in their lives that seem appropriate – chat about and discuss Amy Winehouse and Britney Spears and talk openly
    about the pictures in the papers and the awful waste of
    talent of these stars through their misuse of drugs. “Hope smiles from the threshold of the year to come,.

    [Reply]

  50. home source for income Reviews Says:

    Useful information. Lucky me I discovered your web
    site accidentally, and I’m surprised why this coincidence
    didn’t happened in advance! I bookmarked it.

    [Reply]

  51. keyword research tool Says:

    Thanks for the marvelous posting! I seriously enjoyed reading it, you are a great
    author.I will make certain to bookmark your blog and will often come back sometime soon. I want to encourage you continue your great work, have
    a nice day!

    [Reply]

  52. window casement Says:

    The Advantages of Softwood Casement Windows

    There are many different vinyl casement replacement windows solutions, whether you’re along the way of creating a brand new home otherwise
    you need windows for your existing home. Besides different ones,
    like casement windows, double hung and sash, but there are also lots of materials from hard or soft wood to PVC, aluminium and much more.

    [Reply]

  53. Afslank Info Says:

    Zo ja, dan bent u waarschijnlijk middenin een metabole
    vertraging. De theorie is dat vasten tweemaal weekly vermindert de volledige selectie van energy one neemt in alle
    de weg door elke week. Fruit seizoen in de winter maanden kan vervangen door perziken en aardbeien met
    grapefruits, kanteloep (geschild en sinaasappelen.

    [Reply]

  54. best laser treatment for acne Says:

    I go to see day-to-day some websites and websites to read articles
    or reviews, except this web site gives feature based posts.

    [Reply]

  55. sbo promotion Says:

    I was wondering if you ever thought of changing the layout of
    your site? Its very well written; I love
    what youve got to say. But maybe you could a little
    more in the way of content so people could connect with it
    better. Youve got an awful lot of text for only having one or 2 pictures.
    Maybe you could space it out better?

    [Reply]

  56. Val Says:

    Good day I am so excited I found your site, I really found you by mistake, while I was searching on Digg for something else, Regardless I am
    here now and would just like to say thanks a lot for a
    marvelous post and a all round interesting blog (I
    also love the theme/design), I don’t have time to browse it all at the minute but I have book-marked it and also added your RSS
    feeds, so when I have time I will be back to read much more, Please do
    keep up the superb b.

    Look at my weblog frank kern good karma list machine (Val)

    [Reply]

  57. racing rivals hacks Says:

    As the admin of this web site is working, no doubt very shortly it will be
    renowned, due to its quality contents.

    Visit my website … racing rivals hacks

    [Reply]

  58. Del Says:

    Among the 129 inmates the study was done in abc Canada, with some excruciating results.
    Thus, more damage is likely to be treated with psychotherapy and medications.

    [Reply]

  59. Sleep Aid Says:

    Very rapidly this website will be famous
    among all blogging and site-building people, due to it’s nice articles

    [Reply]

  60. vodafone contact Says:

    Great information. Lucky me I recently found your site by accident (stumbleupon).
    I have book-marked it for later!

    [Reply]

  61. search Says:

    Hey! I could have sworn I’ve been to this website before but
    after browsing through some of the post I realized it’s new to me.

    Anyways, I’m definitely happy I found it and I’ll be bookmarking and checking back frequently!

    My site: search

    [Reply]

  62. Thalia Says:

    My brother recommended I might like this web site. He was totally
    right. This post actually made my day. You cann’t imagine just how much
    time I had spent for this info! Thanks!

    Check out my web blog – after effects audio spectrum tutorial – Thalia -

    [Reply]

  63. bowden flowers Says:

    It’s going to be ending of mine day, however before ending I am reading this
    enormous post to increase my knowledge.

    [Reply]

  64. herpes cure news 2014 Says:

    However, the virus will not move around” your body, if you
    have oral herpes it generally does not mean you necessarily have got genital
    herpes.

    my webpage; herpes cure news 2014

    [Reply]

  65. el libro troll pdf Says:

    This is the perfect blog for everyone who wants to find
    out about this topic. You know a whole lot its almost tough to argue
    with you (not that I actually would want to…HaHa).
    You definitely put a new spin on a topic that has been written about for decades.
    Great stuff, just excellent!

    [Reply]

  66. penile extender study Says:

    Very rapidly this website will be famous among all blogging and site-building users,
    due to it’s fastidious articles

    [Reply]

  67. Forex Marketing Says:

    I really like reading through a post that can make men and women think.
    Also, thank you for allowing for me to comment!

    [Reply]

  68. bluecactus.ca Says:

    If you’ll go browsing you’ll find various web pages that happen to be dedicated
    to promoting the materials you will have to properly costume your own pet cage.
    It is fun to collect the eggs and you are supporting living a greener life style.
    Pine shavings are acceptable given that they are of pet quality and not terribly aromatic.

    [Reply]

  69. Cheap Air Max UK 1 White Cement Says:

    I drop a leave a response whenever I appreciate a article on a site or if I have something to valuable to contribute to the conversation.
    Usually it is a result of the passion communicated in the
    article I browsed. And after this article HEJP’s Blog ? Blog Archive ? Java Socket
    Programming, Handling Multiple Clients. I was excited enough to post a comment :) I actually
    do have a couple of questions for you if it’s okay.
    Could it be only me or does it seem like a few of
    these responses look like they are coming from brain dead people?
    :-P And, if you are writing at other social sites, I would like to follow anything fresh you have to post.

    Would you list all of all your communal pages like
    your Facebook page, twitter feed, or linkedin profile?

    Also visit my site; Cheap Air Max UK 1 White Cement

    [Reply]

  70. jasa seo amos Says:

    Hi there, just became aware of your blog through Google, and found
    that it is really informative. I am going to watch
    out for brussels. I will appreciate if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

    [Reply]

  71. gardner white Says:

    Attractive part of content. I just stumbled upon your site and in accession capital to assert that I acquire actually loved account your blog posts.
    Any way I will be subscribing on your feeds and even I achievement
    you access constantly quickly.

    [Reply]

  72. improve dick size Says:

    The other day, while I was at work, my cousin stole my iphone and tested to see if it can survive a 25 foot drop, just so
    she can be a youtube sensation. My iPad is now broken and she has 83 views.
    I know this is entirely off topic but I had to share it with someone!

    [Reply]

  73. Location vacances Says:

    What’s Happening i’m new to this, I stumbled upon this I
    have discovered It absolutely helpful and it has helped me out loads.
    I’m hoping to contribute & aid other customers like its aided
    me. Good job.

    [Reply]

  74. Rayford Says:

    Howdy! I know this is kind of off topic but I was wondering which blog platform are you using for this
    website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking
    at alternatives for another platform. I would be awesome if you could point me in the direction of
    a good platform.

    [Reply]

  75. streptococcus bacterial infection Says:

    You actually make it seem so easy along with your presentation but I find this topic to
    be really something which I believe I would never understand.
    It sort of feels too complicated and very broad for me.
    I am having a look forward on your next submit, I will attempt to get
    the hang of it!

    [Reply]

  76. liliartcentral.com Says:

    Hi there mates, fastidious piece of writing and nice urging commented here, I am in fact enjoying by these.

    [Reply]

  77. redness pain and swelling are signs of a Says:

    For latest news you have to pay a quick visit internet and on the web I found this
    site as a finest web page for hottest updates.

    [Reply]

  78. great birthday Says:

    Very rapidly this web site will be famous amid all blogging people, due to it’s fastidious articles or reviews

    [Reply]

  79. bakery story cheats yahoo Says:

    Nice post. I learn something new and challenging on websites I stumbleupon everyday.
    It will always be interesting to read articles from other authors and use something from
    their websites.

    [Reply]

  80. http://pharmacyreviewer2014.com Says:

    I do accept as true with all the ideas you have offered in your post.
    They’re very convincing and can certainly work. Still, the
    posts are very quick for newbies. May you please prolong
    them a little from subsequent time? Thank you for the post.

    [Reply]

  81. up skin Says:

    Hi, I think your website might be having browser compatibility issues.

    When I look at your blog in Firefox, it looks
    fine but when opening in Internet Explorer, it
    has some overlapping. I just wanted to give you a
    quick heads up! Other then that, terrific blog!

    [Reply]

  82. http://pdfpills.com/ Says:

    This is my first time pay a quick visit at here and i am truly
    happy to read everthing at alone place.

    [Reply]

  83. website design Says:

    WOW just what I was looking for. Came here by searching for press release

    [Reply]

  84. http://drugstorepdfsearch.com/ Says:

    Definitely believe that that you stated. Your favorite justification appeared
    to be at the web the easiest factor to be mindful of.
    I say to you, I certainly get irked while other people think about worries that they plainly
    don’t recognize about. You controlled to hit the nail
    upon the top as neatly as defined out the entire thing without having side-effects , folks could take a signal.
    Will probably be again to get more. Thank you

    [Reply]

  85. brilliantpressrelease.com Says:

    Can I simply say what a comfort to find somebody who genuinely knows what they’re discussing on the internet.
    You definitely know how to bring a problem to light
    and make it important. A lot more people should check this out and understand
    this side of your story. I was surprised that you are not more popular because you most certainly have the gift.

    [Reply]

  86. pebblestone tile Says:

    Similarly, bathroom remodeling services in Greenwich
    are also necessary to maintain the aesthetics of your own bathroom.
    In addition to that, you should not overlook to examine with
    him overages and other service fees that will be addressed throughout and
    following the development. In the event that you know a
    Houston bathroom remodeling company that is offering bathroom remodeling service in your area with good reviews,
    then you need to take advantage of this and hire them for a job that you want.

    [Reply]

  87. funny Commercials Says:

    Hey there I am so grateful I found your web site, I really found you
    by error, while I was looking on Google for something else, Nonetheless I am
    here now and would just like to say cheers for a incredible post and a all round interesting blog (I also love the theme/design), I don’t
    have time to read through it all at the moment but
    I have saved it and also added your RSS feeds, so
    when I have time I will be back to read more, Please do
    keep up the superb work.

    [Reply]

  88. called natural Says:

    WOW just what I was searching for. Came here by searching for natural penis male

    [Reply]

  89. enhancement free Says:

    Just desire to say your article is as surprising.
    The clarity in your post is just nice and i can assume you’re an expert
    on this subject. Fine with your permission let me to grab
    your feed to keep updated with forthcoming post. Thanks a million and please continue the gratifying
    work.

    [Reply]

Leave a Reply