【问题标题】:Putting a condition if socket does not get a message如果套接字没有收到消息,则设置条件
【发布时间】:2017-05-15 16:50:10
【问题描述】:

如果我在 java 中的套接字没有收到任何消息,我想执行一些任务。但我认为 socket.accept() 会等到它收到一条消息。 以下是我为此目的编写的代码。

while (true) {
                clientSocket = serverSocket.accept();
                is = new DataInputStream(clientSocket.getInputStream());
                message = is.readLine();
                check=0;
                if (message != null) {
                    System.out.println("recieved :" + message);
                    if (message.contains("Dead")) {
                        System.out.println("Player is Dead");

                    else{
                        System.out.println("akakak");
                    }

                }
                else{
          // the code here should run if the socket does not receive any message
                    System.out.println("noeoeo");
                }

            }

【问题讨论】:

标签: java multithreading sockets networking


【解决方案1】:

我认为socket.accept() 会等到收到消息。

没有。 ServerSocket.accept() 在收到入站连接之前会阻塞。你正在寻找的是Socket.setSoTimeout()SocketTimeoutException

// The code here should run if the socket does not receive any message

没有。如果readLine() 返回null,则对等方已断开连接,您也应该这样做。而不是打印noeoeo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2021-11-19
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多