簡體   English   中英

如何將所有消息發送到客戶端(Java服務器)

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

我已經建立了一個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();
   }
     }

如果我理解正確,則希望將消息發送到連接到服務器的其余客戶端。

為此,您的服務器必須跟蹤與其連接的所有客戶端套接字 一種方法可能是在服務器端保留客戶端套接字的列表,並且當服務器接收到消息時,遍歷該列表並將消息發送給每個客戶端。

檢查使用相同機制的此鏈接: https : //stackoverflow.com/a/27911355/891092

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM