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


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

	ClientHandler(Socket s) {
		socket = s;

	public void run() {

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


		try {
		} 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:


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);

		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 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.

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

  1. adidas Says:

    its good but not so good


  2. mrutyunjay sawant Says:



  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!


  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


  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


  6. autocom Says:

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


  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


  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.


  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.


  10. akshay Says:

    Nice program for newbie of socket programming. Thanks


  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?


  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.


  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.


  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.


  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
    Is there a way I can transfer all my wordpress posts into it?
    Any kind of help would be greatly appreciated!


  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.


  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.


  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


  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.


  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


  21. projektowanie stron www moji poznanici pozivnica Says:



  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.


  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.


  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


  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


  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.


  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.


  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.


  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.


  30. csr racing download Says:

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


  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.


  32. 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.


  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.


  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.


  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.


  36. 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 ::


  37. 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 – -


  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!


  39. 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.


  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!


  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.


  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.


  43. Transformers Age of Extinction Cheats Says:

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


  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.


  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.


  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


  47. Samba Télécharger Says:

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


  48. 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?


  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,.


  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.


Leave a Reply