无法使用java中的serversocket多次发送请求

h4cxqtbf  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(373)

我在netbeans中有一个简单的客户机-服务器应用程序,它向服务器发送登录请求,并侦听服务器的答案。
我在客户端的构造函数中声明这些代码:

try {
        socket = new Socket("localhost", 12345);
        oos = new ObjectOutputStream(socket.getOutputStream());
        ois = new ObjectInputStream(socket.getInputStream());
    }catch (Exception e) {
        e.printStackTrace();
    }

和请求发送者时单击按钮 str 是登录信息:

public void request_login(String str) {
    try {

        this.oos.writeInt(1);
        this.oos.writeUTF(str);
        this.oos.flush();
        System.out.println("CLIENT: Sent!");

        int responseCode = this.ois.readInt();
        if (responseCode == Protocol.OK) {
            //OK handler
        }else {
        //Fail handler
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NullPointerException ee) {
                ee.printStackTrace();
            }

}

这是我的服务器:

public ServerATM() {
    try {
                this.serversocket = new ServerSocket(12345);
                System.out.println("Server is listening!");

                for(;;){
                        Socket socket = this.serversocket.accept();
                        Thread t = new ClientThread(socket);
                        t.start();
                }
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }

}

以及 ClientThread 班级:

public ClientThread(Socket socket) {
    this.socket = socket;
    try {
                this.ois = new ObjectInputStream(socket.getInputStream());
                this.oos = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
}

private void processThread() {
    try {
        int requestCode = this.ois.readInt();
        switch(requestCode) {
            case 1:
                String request = ois.ReadUTF();
                // Handle the code with the request.
                //Then return the result for client
                oos.writeInt(5);
                oos.flush();
                break;
            case 2:
                break;
        }
    } catch (IOException ex) {
        Logger.getLogger(ClientThread.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void run(){
    processThread();
}

代码在第一次单击时运行良好。但当我更改输入字符串并再次单击时,代码就挂起了。这个 processThread 只在第一次单击时调用一次,第二次单击不会调用它,因此它不会执行我的代码。
看起来当一个请求被发送时,它会在服务器中创建一个新线程,但在本例中,它已经被创建了,所以不会再次运行。不管怎样,我是否可以多次发送请求,服务器将全部侦听?
谢谢您

8wigbo56

8wigbo561#

呼叫 processThread() 方法中的方法 run()ClientThread 使用while循环。

public void run(){
    while(true) processThread();
}

希望这会有帮助。。

相关问题