zeeshan nisar
zeeshan nisar

Reputation: 573

send message from server to all connected clients

How can i send a message from server to all connected clients using sockets or how can i send message from server to any specific client. I have the concept of how to do it like i have to make a list of all the clients connected to server and then by iterating each client i can send message but i will be thankful if any one can help me by code.I have searched many codes but i didn't get any considerable help from them Code shouldn't be GUI based. Thanks in advance.Sorry for my bad English.

Upvotes: 1

Views: 1786

Answers (1)

Michael Markidis
Michael Markidis

Reputation: 4191

Assuming you are using a java.net.ServerSocket, you could keep a HashMap of all client connections using the following:

Map<Integer, java.net.Socket> clients = new HashMap<Integer, java.net.Socket> ();

Caching a Client

Now, whenever you receive a new client connection to your server you can add the new client to the map:

socket = serverSocket.accept();

// Add the socket to a HashMap
clients.put(socket.getPort(), socket);

When you want to send a message to all of your clients:

Iterating through all your clients:

for (Iterator<Integer> iter = clients.keySet().iterator(); iter.hasNext(); )
{
    int key = iter.next();

    java.net.Socket client = clients.get(key);

    // Sending the response back to the client.
    // Note: Ideally you want all these in a try/catch/finally block
    OutputStream os = client.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os);
    BufferedWriter bw = new BufferedWriter(osw);
    bw.write("Some message");
    bw.flush();
}

Notes:

  • You will want a way to purge clients from the HashMap; especially if your server is long-lived.
  • Ideally, you will want to put all the I/O code (to the clients) in a try/catch/finally block

Upvotes: 1

Related Questions