Link to home
Start Free TrialLog in
Avatar of lwinkenb
lwinkenb

asked on

Server programming question

I'm writing a server in java that uses threads to have multiple clients connect to the same serversocket.  My question is this:  How can I exchange info between the connected clients?

For instance, if there are 3 clients connected, and clientA sends some information to the server; how can I have the server send that info to ALL the connected clients?

Here is what my server looks like:
ServerSocket server_socket;
try{
    server_socket = new ServerSocket(1000);
  } catch (IOException e) {
    System.out.println("Could not listen on port 1000");
    System.exit(-1);
  }
  while(true){
    ServerThread newConnection;
    try{
      newConnection = new serverThread(server_socket.accept());
      newConnection.start();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
  }
Avatar of fivesigmaevent
fivesigmaevent

You could try to pass a shared buffer to the thread constructor.

newConnection = new serverThread(server_socket.accept(), sharedBuffer );

Use the buffer to communicate between threads. You probably should synchronize access to the buffer so not to corrupt any data.
Avatar of lwinkenb

ASKER

Im not really sure how a shared buffer works.  Could you point me to an example?
Sounds like an event model is what you are looking for.  The server could keep a list of ServerThread connections and notify each whenever a message comes in.  Just make sure to remove the ServerThread from the list when closed to avoid a memory leak.
could you post an example to get me started warsql?
ASKER CERTIFIED SOLUTION
Avatar of warsql
warsql

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I was going to change what I said about passing a buffer to passing "this" and invoking a callback for each thread. Looks like warsql beat me to it!

This community is awesome.
Thanks a lot, perfect answer.
After further thought, the connections variable will be accessed by different threads, so you will want to synchronize around its access.

synchronized(connections) {
// add to connections
}

and

syncronized(connections) {
// iterate through connections
}

just in case a client connects while a message is being broadcast.