Send messages to specific clients using java

How to send a message from the server to any specific client. I have a concept on how to do this, as if I have to make a list of all the clients connected to the server, and then, iterating over each client, I can send a message, but I will be grateful if someone can help me with the code. I searched for many codes, but I did not get any significant help from them. The code should not be based on a graphical interface. Thanks in advance. I apologize for my poor English. This is my code in which a message is sent to all clients, but I want to send a message to the client of my choice using ipaddress clients

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

// Add the socket to a HashMap
clients.put(socket.getPort(), socket);
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();
}
+4
source share
5 answers

, , . ,

Map<String, Socket> sockets = new HashMap<String,Socket>();
...
ServerSocket ss = ...;
Socket s = ss.accept();
String username = getUserName(s);
sockets.put(username, s);

, , Socket

+1

, Client:

class Client
{
   private String userName;
   private String ipAddress;
   private java.net.Socket socket = null;

   public Client (String userName, String ipAddress, java.net.Socket socket)
   {
      this.userName = userName;
      this.ipAddress = ipAddress;
      this.socket = socket;
   }

   public java.net.Socket getSocket()
   {
       return this.socket;
   }
}

, , ipAddres Client.

socket = serverSocket.accept();

// get the username from the socket
// get the ipAddress from the socket
Client c = new Client(userName, ipAddress, socket);

// Add the client to a HashMap
clients.put(userName + ":" + ipAddress, c);

ipAddress:

public void sendToOneClient (String userName, String ipAddress, Map<String, Client> clients)
{
    Client c = clients.get(userName + ":" + ipAddress);

    java.net.Socket socket = c.getSocket();

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

Socket.getInetAddress() , IP-, . , String[] ArrayList<String>. :

ArrayList<String> addresses;
//TODO: Add things to 'addresses'

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

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

    //Checking to make sure it a client we want to send to.
    if (addresses.contains(client.getInetAddress().toString()) {
        // 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();
    }
}

HashMap InetAddress.

+1

, , , id, int String, Socket. ArrayList ( ) , , .

0

This is what I have done for my program. Here I used the string “→” to indicate that the message should be sent to a specific user. (for example: “Ross → Hi Ross What Up?” means that the message should be sent to the user with the name “Ross”). I used a HashMap (named "WritersMap") to store details as KEY-VALUE pairs. The key will be the name of the user who sends the particular message, and the value will be that message. "in" is an instance of BufferedReader.

while (true) {
                    String input = in.readLine();
                    if (input == null) //if there is no input,do nothing
                    {
                        return;
                    }

                    //when a user sends a message to a specific user
                    else if(input.contains(">>"))   //checks whether the message contains a >> 
                    {
                        String person=input.substring(0,input.indexOf(">"));    //extract the name of the destination user 
                        for(HashMap.Entry<String,PrintWriter> entry:writersMap.entrySet())  //find the destination user from the users list 
                        {
                            if(entry.getKey().matches(person))  //if the destination user is found 
                            {
                                PrintWriter writer=entry.getValue();
                                writer.println("MESSAGE " + name + ": " + input);
                            }
                        }
                    }
                    else    //when a user sends a broadcast message to all users 
                    { 

                        for(HashMap.Entry<String,PrintWriter> entry:writersMap.entrySet())  //find the destination user from the users list 
                        {
                            PrintWriter writer=entry.getValue();
                            writer.println("MESSAGE " + name + ": " + input);
                        }
                    }
                }
0
source

All Articles