【问题标题】:client-server chat program problem on serversocketserversocket上的客户端-服务器聊天程序问题
【发布时间】:2018-12-09 20:38:32
【问题描述】:

我正在做一个客户端服务器聊天项目。其中客户端 A 和客户端 B 应该连接到服务器。我可以将客户端 A 与服务器连接,但客户端 B 出现问题。 我想将客户端 A 和客户端 B 与服务器连接。客户端 A 连接成功。而且我想与客户 A 和客户 B 沟通。但如果有人帮助我,我会失败,我会很感激。 谢谢

    String msgin = "";
try{
    ss= new ServerSocket(5000);
    s= ss.accept();
    din= new DataInputStream(s.getInputStream());
    dout= new DataOutputStream(s.getOutputStream());
    while(!msgin.equals("exit")) {
        msgin = din.readUTF();
        msg_area.setText(msg_area.getText().trim()+"\n Client A:\t"+msgin);
           }
}catch(IOException e){

}
String msgIn = "";
try{
    ss= new ServerSocket(6000);
    s= ss.accept();

    din= new DataInputStream(s.getInputStream());
    dout= new DataOutputStream(s.getOutputStream());
    while(!msgIn.equals("exit")) {
        msgIn = din.readUTF();
        msg_area.setText(msg_area.getText().trim()+"\n Clint B:\t"+msgIn);
           }
}catch(Exception e){

}

客户A

java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyClientSocket().setVisible(true);
        }
    });
     try{
        s = new Socket("127.0.0.1",5000);
        din = new DataInputStream(s.getInputStream());
        dout = new DataOutputStream(s.getOutputStream());
        String msgin="";
        while(!msgin.equals("exit")){
        msgin = din.readUTF();
        msg_area.setText(msg_area.getText().trim()+"\n Server:\t"+msgin);

        }

    }catch(Exception e){

}

客户乙

java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MyClientServerB().setVisible(true);
        }
    });

    try{
        s = new Socket("127.0.0.1",6000);

        din = new DataInputStream(s.getInputStream());
        dout = new DataOutputStream(s.getOutputStream());
        String msgIn="";
        while(!msgIn.equals("exit")){
        msgIn = din.readUTF();
        msg_area.setText(msg_area.getText().trim()+"\n Server:\t"+msgIn);

        }

    }catch(Exception e){

}

【问题讨论】:

    标签: java javafx client-server


    【解决方案1】:

    为了允许多个客户端同时连接到服务器,您需要使用多线程。尝试为每个连接的客户端创建一个新线程。服务器是长时间运行的程序,因此它应该通过循环不断地监听新的客户端连接。

    以下是您可以考虑尝试的逻辑:

    try {
            serverSocket = new ServerSocket(8080);
        } catch (IOException io) {
            io.printStackTrace();
    }
    
    while (true) {
    
            Socket clientSocket;
            try {
                clientSocket = serverSocket.accept();
            } catch (IOException io) {
                io.printStackTrace();
            }
    
            Thread t = new Thread(new Runnable() {
                 // handle each client independently 
            }
            t.start();
    
     }
    

    【讨论】:

    • 现在您有两台服务器,而不是一台。如果你想让两个客户端同时连接到同一个服务器,你需要多线程。
    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 2020-03-25
    • 2014-04-18
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多