简体   繁体   中英

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)

  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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