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.

25 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]

Leave a Reply