简体   繁体   English

如何将所有消息发送到客户端(Java服务器)

[英]How to send all the message to the client(java server)

I have built a java server and I want to send messages to other clients .This is my client peer code.The program is able to print to the screen the message that one client sent to the server(but only the message that client sent) for example: new user:hi(this is what the server receives and also what the text client console shows) 我已经建立了一个Java服务器,我想向其他客户端发送消息。这是我的客户端对等代码。该程序能够将一个客户端发送到服务器的消息打印到屏幕上(但仅将客户端发送的消息打印到屏幕上)例如:new user:hi(这是服务器接收的内容,也是文本客户端控制台显示的内容)

  import java.io.IOException;
  import java.io.ObjectOutputStream;
     import java.net.Socket;
    import java.util.Scanner;
       import java.util.logging.Level;
      import java.util.logging.Logger;

       public class ClientPeer extends Thread{


String username;
Socket socket;
public ClientPeer(String username,Socket socket)
{
    this.username=username;
    this.socket=socket;
}
@Override
public synchronized void run()
{
    Scanner input=new Scanner(System.in);
    String string=input.nextLine();
    while(true)
    {
        if(!string.startsWith("/w") && !string.equals("exit"))
        {
            try {
                sendMessage(string);
            } catch (IOException ex) {
                Logger.getLogger(ClientPeer.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(username+":"+string);
        }
        string=input.nextLine();


    }

}
public void sendMessage(String message) throws IOException
{
    ObjectOutputStream object=new ObjectOutputStream(socket.getOutputStream());
    object.writeObject(new Message(message,username));
    object.flush();


}
public void sendMessage(String message,String whoto) throws IOException
{
    ObjectOutputStream object2=new   ObjectOutputStream(socket.getOutputStream());
    object2.writeObject(new PrivateMessage(username,message,whoto));
    object2.flush();
   }
     }

If I understood it right you want to send the message to rest of the clients connected to the server. 如果我理解正确,则希望将消息发送到连接到服务器的其余客户端。

For that your Server has to keep track of all the client sockets connected to it. 为此,您的服务器必须跟踪与其连接的所有客户端套接字 An approach could be to keep a list of the client sockets in the server side, and when the server receives a message, loop through the list and send message to each of the clients. 一种方法可能是在服务器端保留客户端套接字的列表,并且当服务器接收到消息时,遍历该列表并将消息发送给每个客户端。

Check this link which uses the same mechanism: https://stackoverflow.com/a/27911355/891092 检查使用相同机制的此链接: https : //stackoverflow.com/a/27911355/891092

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM