【问题标题】:send message to specific clients using java使用 java 向特定客户端发送消息
【发布时间】:2018-06-24 19:06:02
【问题描述】:

如何从服务器向任何特定客户端发送消息。我有如何做到这一点的概念,就像我必须列出所有连接到服务器的客户端然后通过迭代每个客户端我可以发送消息但如果有人可以通过代码帮助我,我将不胜感激。我已经搜索过许多代码,但我没有从他们那里得到任何可观的帮助 代码不应该是基于 GUI 的。在此先感谢。抱歉我的英语不好。 这是我的代码,其中消息发送给所有客户端,但我想使用客户端 ipaddress 将消息发送给我选择的客户端

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();
}

【问题讨论】:

  • 我刚刚看到您将此作为单独的问题添加。这取决于您要如何识别要挑选的客户。你知道你想怎么做吗?
  • 是的,先生,一旦客户端连接到服务器,它就会将他的 ipadress 和用户名发送到服务器,现在使用 ipadressess,我想向任何特定客户端发送消息,我有一个选项是,如果我想将消息发送到 IP 地址 192.168.1.1 的客户端,然后我会将消息和 IP 地址发送给所有客户端,然后简单地在客户端应用检查哪个客户端具有该 IP 地址,如果其中任何一个具有该 IP 地址,则向他显示该消息

标签: java


【解决方案1】:

我要做的是创建一个客户端类:

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;
   }
}

我不会只将套接字和端口号添加到映射中,而是将 userName 和 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();
}

【讨论】:

    【解决方案2】:

    我会使用 Socket.getInetAddress() 并将结果与​​您想要发送到的任何 IP 进行比较。就个人而言,我会使用 String[]ArrayList&lt;String&gt;。这是一个例子:

    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's 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();
        }
    }
    

    或者,您可以通过 InetAddress 将套接字存储在 HashMap 中。

    【讨论】:

      【解决方案3】:

      您可以存储您希望如何查找客户端与他们所在的套接字之间的关系。这样做的自然方法是使用地图,例如

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

      显然,在此示例中,客户端必须以您希望在建立 Socket 连接后接收到的格式发送他/她的用户名

      【讨论】:

      • 我认为应该是 sockets.put(userID,s) @ControlAltDel
      【解决方案4】:

      我发现创建一个对象类型是有效的,它可以同时包含一个唯一的名称或 ID,无论是 intString 还是 Socket。您可以将此对象的实例存储在 ArrayList(或任何其他列表)中并遍历它们以搜索您要使用的名称或 ID。

      【讨论】:

        【解决方案5】:

        这就是我为我的程序所做的。这里我使用“>>”字符串来指定应该向特定用户发送消息。 (例如:“Ross>>Hi Ross What's Up?”表示消息应该发送给名为“Ross”的用户)。我使用 HashMap(名为 'WritersMap')将详细信息保存为 KEY-VALUE 对。 Key 将是发送特定消息的用户的名称,而 Value 将是该消息。 'in' 是一个 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);
                                }
                            }
                        }
        

        【讨论】:

          猜你喜欢
          • 2016-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多