socket通信中的java.io.EOFException问题
各位师兄:
大家好。最近在做一个SOCKET通信程序。如下:
public static void main(String[] args) {
try
Socket telSocket = new Socket(host, port);
DataInputStream tel_in = new DataInputStream(telSocket.getInputStream());
OutputStream tel_out = telSocket.getOutputStream();
//////////////一连接上后就发送一个请求指令,这样服务端就会回送信息
String note = "ask readyok" + "\n";
tel_out.write(note.getBytes());
tel_out.flush();
System.out.println("send note is ok!");
////当连接保持的时候进行收发信息
while (!telSocket.isClosed()) {
tel_len = tel_in.readInt();
System.out.println(tel_len);
if (tel_len > 4092) {
tel_len = 4092;
}
byte buf[] = new byte[tel_len];
System.out.println("read is ok!");///接收信息OK
tel_in.read(buf);
String revice = new String(buf).trim();
System.out.println(revice);///打印显示出接收的信息
///每收到信息后就要向服务端发送一条心跳确认
String heard = "heard is jump"+ "\n";
tel_out.write(heard.getBytes());
tel_out.flush();
System.out.println("send heard is ok!"+heard);
}
}
catch (Exception e) {
System.out.println("connect telnet fail:" + host + ":" +
port + e);
}
}
程序运行调试的时候,我发现程序运行到循环体即while (!telSocket.isClosed()) 内时,第一次收发是正常的,第二次运行到tel_len = tel_in.readInt();就跳出异常了显示:java.io.EOFException!!!
我试了一下,如果把向服务端发送心跳确认的这部分代码屏蔽掉,那就可以读取正常了.这是为什么呢???如何能做到收发正常呢???
谢谢赐教.