Reputation: 573
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
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> ();
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);
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();
}
Upvotes: 1