How to send all the message to the client(java server)

笑着哭i 提交于 2020-01-06 14:12:59

问题


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)

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

回答1:


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/questions/28027667/how-to-send-all-the-message-to-the-clientjava-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!