套接字客户端断开时的无限循环

时间:2013-10-07 16:54:30

标签: java multithreading sockets null serversocket

我实现了一个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;
    }

}

1 个答案:

答案 0 :(得分:4)

append方法永远不会返回null,所以这不对,永远不会输入if - 分支:

  if (inString.append((String) inStream.readLine()) == null) {

代码应该看起来更像这样:

  String line = inStream.readLine();
  if (line == null) {
      ...
  } else {
      inString.append(line);
      ...
  }