Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 套接字客户端,空闲超时_Java_Sockets - Fatal编程技术网

Java 套接字客户端,空闲超时

Java 套接字客户端,空闲超时,java,sockets,Java,Sockets,如果客户端在某个时间内没有接收/发送任何消息,是否仍要为客户端套接字设置超时 以下是我的代码片段: try { mainSocket = new ServerSocket(portNumber); clientSocket = mainSocket.accept(); in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); out = new PrintWriter(client

如果客户端在某个时间内没有接收/发送任何消息,是否仍要为客户端套接字设置超时

以下是我的代码片段:

try {
  mainSocket = new ServerSocket(portNumber);
  clientSocket = mainSocket.accept();
  in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  out = new PrintWriter(clientSocket.getOutputStream(), true);

} catch (IOException ex) {
  Logger.error(this, "failed to accept connection. Error was " + ex.getMessage());
}

while (reading) {
  try {

    char[] arr = new char[2048];
    ch = 0;
    ch = in.read(arr);
    if (ch < 0) {
      reading = false;
    }
    else {
    //process message
  } catch (IOException ex) {
    Logger.error(this, ex);
  }
}
试试看{
mainSocket=新服务器套接字(端口号);
clientSocket=mainSocket.accept();
in=new BufferedReader(新的InputStreamReader(clientSocket.getInputStream());
out=新的PrintWriter(clientSocket.getOutputStream(),true);
}捕获(IOEX异常){
Logger.error(这是“无法接受连接。错误为”+ex.getMessage());
}
边读{
试一试{
char[]arr=新字符[2048];
ch=0;
ch=英寸读数(arr);
if(ch<0){
阅读=错误;
}
否则{
//处理消息
}捕获(IOEX异常){
记录器错误(此,例如);
}
}
现在我想做的是,如果在x秒之后clientSocket没有收到任何消息,它将退出循环,关闭连接并重新启动接受连接

我知道如何关闭连接并重新开始接受连接,但我仍然无法理解其余的部分。是否还有其他方法可以实现这一点

谢谢你的帮助