基本上,我做了一个程序,通过将文本编码成6位数的二进制形式,将文本发送到另一台计算机,以节省空间,但这不是重点,它发送数据的方式才是重点。它使用插座连接。如果它是0,它会立即断开连接,但如果它是1,它会等待一定的时间,然后关闭套接字。下面是我用来发送文本的代码:
*encoded是布尔值的数组列表
for(int i = 0;i < encoded.size();i+=6){
for(int b = i; b < i+6; b++){
Socket s1 = new Socket(ip,5576);
if(encoded.get(b) == true){
Thread.sleep(2000);
}
s1.close();
}
}服务器代码是这样的:
while(true){
Socket s = ss.accept();
if(first){
first = false;
continue;
}
Thread.sleep(1000);
if(!s.isClosed()){
encoded.add(true);
zerosInRow = 0;
System.out.println(1);
}else{
encoded.add(false);
zerosInRow++;
System.out.println(0);
}
if(zerosInRow >= 6){
encoded.remove(encoded.size()-1);
encoded.remove(encoded.size()-2);
encoded.remove(encoded.size()-3);
encoded.remove(encoded.size()-4);
encoded.remove(encoded.size()-5);
encoded.remove(encoded.size()-6);
break;
}
}但问题是,当我运行它时,它只输出1
发布于 2017-12-19 07:45:14
Socket.isClosed()会告诉您是否已关闭此套接字。
它不会告诉您任何有关连接状态的信息。
要确定对等项是否在超时内关闭了连接,您需要设置读取超时并执行读取。如果您获得了SocketTimeoutException,则连接仍处于打开状态。如果read()返回-1,则它已关闭。
https://stackoverflow.com/questions/47876561
复制相似问题