0

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

4 Answers4

0

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

Community
  • 1
  • 1
Shash
  • 4,160
  • 8
  • 43
  • 67
  • 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
0

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.

Tao Feng
  • 89
  • 2
0

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

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
-1

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.

samuirai
  • 762
  • 1
  • 9
  • 25