我已经实现了一个 Java 多线程套接字服务器。它工作正常,并为每个新的客户端连接创建一个新线程。但是当客户端切断 TCP 连接时,我有一个错误,服务器进入无限循环,并且每个循环我都收到此消息:
ERROR : Bad Frame !!! : null
我尝试调试执行并更改if else
条件,但是当客户端断开连接时总是存在相同的错误。
这是我的服务器代码
public class TCPSockServer implements Runnable {
Socket sock;
static int counter = 0;
private static int TIMEOUT = 50000;
private static int MAX_TIMEOUT = 100000;
long lastReadTime;
public TCPSockServer(Socket sock) {
this.sock = sock;
}
public static void main(String[] args) {
try {
ServerSocket serverSock = new ServerSocket(12000);
System.out.println("TCPSockServer : Listening to PORT 12000 ...");
while (true) {
Socket newSock = serverSock.accept();
counter++;
InetAddress addr = newSock.getInetAddress();
System.out.println("TCPSockServer : Connection Number : "+ counter);
System.out.println("TCPSockServer : Connection made to "
+ addr.getHostName() + " : (" + addr.getHostAddress()
+ ")");
newSock.setSoTimeout(TIMEOUT);
newSock.setKeepAlive(true);
new Thread(new TCPSockServer(newSock)).start();
}
} catch (IOException e) {
System.err.println("Trackiz: Main : ERROR Connection Failed");
e.printStackTrace();
}
}
@Override
public void run() {
int clientID = counter;
try {
BufferedReader inStream = new BufferedReader(new InputStreamReader(
sock.getInputStream()));
StringBuilder inString = new StringBuilder();
String frame = null;
PrintStream outStream = new PrintStream(sock.getOutputStream());
while (true) {
if (inString.append((String) inStream.readLine()) == null) {
System.out.println("TCPSockServer : CLIENT NOT CONNECTED");
sock.close();
break;
} else {
lastReadTime = System.currentTimeMillis();
frame = inString.toString();
if (cond1(frame)) {
......
}else{
system.err.println("\nERROR : Bad Frame !!! : "+frame); // why it enter this else in an infinit loop
}
outStream.println(provt.sendCommand("TCPSockServer : ACK TO CLIENT"));
inString = null;
inString = new StringBuilder();
}
}
inStream.close();
outStream.close();
sock.close();
} catch (SocketTimeoutException e) {
if (!isConnectionAlive()) {
System.out.println("\nCONNECTION TERMINATED FROM CLIENT !"
+ clientID);
logger.log(Level.SEVERE, "TCPSockServer : Connection terminated with Client");
try {
sock.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
// TODO sendHeartBeat();
System.out.println("Sending HeartBeat ...");
}
e.printStackTrace();
} catch (IOException e) {
System.err.println("TCPSockServer : Connection Timeout. Try to reconnect !");
e.printStackTrace();
}
}
public boolean isConnectionAlive() {
return System.currentTimeMillis() - lastReadTime < MAX_TIMEOUT;
}
}