I am proceeding to make a code for handling multiple clients in socket programming but i am not having idea for even the algorithm. I dont know how to proceed. Can anyone help me with the algorithm ? Thanks in Advance
-
3The "algorithm" is probably "multi-threading"... – Oliver Charlesworth Mar 15 '12 at 13:36
-
either multi-threading (pthreads) or multiprocess (fork). – twain249 Mar 15 '12 at 13:39
-
1What kind of protocol? It's quite common to handle multiple UDP clients from a single-threaded server. Certainly doable with TCP too, just use `select()`. – unwind Mar 15 '12 at 13:42
-
7There is a huge variety of techniques, summarized in the [C10K overview](http://www.kegel.com/c10k.html), which also has a good bibliography on the subject. – bereal Mar 15 '12 at 13:42
4 Answers
The one which I think would be good is by having a multithreaded server with each thread listening on a single port or multiple ports.
Though there is a possibility of creating a multiprocess server I still recomend using a multi-threaded one. Reasons are in here
-
First, it any case, there is a single thread which is actually _listening_ the port (the one that calls `accept()`). Second, to recommend a multi-threaded over multiprocess is similar to recommending a fork over a spoon not asking what is on the plate. – bereal Mar 15 '12 at 16:13
I think maybe you should try to use either event-driven model(like select()) or multi-thread model. It depends on what you intend to do.

- 89
- 2
I would download the Apache code - It achieves this and seems to be a reasonable algorithm.

- 59,252
- 17
- 87
- 127
I wrote a simple chat in Java once. You can check out the source here: github.com/Samuirai/Java
The basic design is the following:
ServerSocket serverSocket = new ServerSocket(4444);
System.out.println("Server started");
while (true) {
Socket client = serverSocket.accept();
System.out.println("Client connected");
ClientConnection conn = new ClientConnection(client, this);
this.connections.add(conn);
new Thread(conn).start();
}
The Server waits for a client to connect. When a Client connects, it adds a new Connection to a List and starts a Thread which handles the connection with the Client. The Project has three important files you should check out: ChatServer, ChatClient and ClientConnection. I hope the code is easy to understand.

- 762
- 1
- 9
- 25