服务器:套接字在读取流功能时在不可预测的时间内挂起

Server: Socket hangs within unpredictable period time at read stream function

我写了一个 Java 套接字服务器,它将保持连接直到客户端断开连接。我的客户端代码将继续向此服务器应用程序推送消息。

但是当我 运行 那些程序一段时间后,我似乎也出现了一种不寻常的情况,即服务器在不可预测的时间内从客户端读取输入流时会挂起。它总是挂在 inData.read(b),因为当这个问题发生时,我看到它在日志上打印 "receiving..."”;即使我杀死了我的客户端,服务器应用程序仍然挂在那里。

但是当我在出现此问题后 运行s 服务器应用程序的控制台上按 Ctrl+C 时,它将继续工作。真烦人。

有没有办法很好地解决这个Unusual问题?

服务器代码:

    static ServerSocket server;

    try {
        server = new ServerSocket("1234");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Socket socket = null;
    String inIp = null;
    BufferedInputStream inData;
    BufferedOutputStream outData;

    while (true) {
        try {
            synchronized (server) {
                socket = server.accept();
            }
            inIp = String.valueOf(socket.getInetAddress());
            if (Log4j.log.isEnabledFor(Level.INFO)) {
                Log4j.log.info("Incoming connection " + inIp);
            }
            while (true) {
                inData = new BufferedInputStream(socket.getInputStream());
                outData = new BufferedOutputStream(socket.getOutputStream());
                String reply = "Hey";

                byte[] b = new byte[10240];
                String data = "";
                int length;

                if (Log4j.log.isEnabledFor(Level.INFO)) {
                    Log4j.log.info("InetAddr = " + inIp + ", receiving...");
                }


                // read input stream
                length = inData.read(b);
                data += new String(b, 0, length);
                if (Log4j.log.isEnabledFor(Level.INFO)) {
                    Log4j.log.info("Data Length: " + length + ", Received data:  " + data);
                }


                // output result
                outData.write(reply.getBytes());
                outData.flush();
            }
        } catch (Exception e) {
            String tempStr = e.toString();
            Log4j.log.error("Service error during executing: " + tempStr);
        }
    }

客户代码:

    Socket client = new Socket();
    InetSocketAddress isa = new InetSocketAddress("127.0.0.1", "1234");
    String data = "Hi";

    while(true) {
        try {
            if(!client.isConnected())
                client.connect(isa, 30000);

            BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
            BufferedInputStream in = new BufferedInputStream(client.getInputStream());

            // send msg
            out.write(data.getBytes());
            out.flush();


            System.out.println("Message sent, receiving return message...");


            // get return msg
            int length;
            byte[] b = new byte[10240];

            // read input stream
            length = in.read(b);
            retMsg = new String(b, 0, length);

            System.out.println("Return Msg: " + retMsg);

            Thread.sleep(60000); 

        } catch (java.io.IOException | InterruptedException e) {
            System.out.println("Socket Error!");
            System.out.println("IOException :" + e.toString());
        }
    }
try {
    server = new ServerSocket("1234");
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

不要这样写代码。 catch块应该在最后,所有依赖于new ServerSocket成功的代码应该在try块内。

synchronized (server) {
    socket = server.accept();
}

这里不需要同步。

while (true) {
    inData = new BufferedInputStream(socket.getInputStream());
    outData = new BufferedOutputStream(socket.getOutputStream());

很大一部分问题(如果不是全部)都在这里。每次围绕此循环,您都会不断创建新的缓冲流,这意味着先前流缓冲的任何内容都将被丢弃。所以你正在失去输入。您应该在循环之前创建这两个流。

while(true) {
    try {
        if(!client.isConnected())
            client.connect(isa, 30000);

这毫无意义。去掉。您还没有显示 client 套接字是如何创建的,但是如果您创建它时未连接,您应该在进入此循环之前连接它。

        BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
        BufferedInputStream in = new BufferedInputStream(client.getInputStream());

在这里,您必须再次在循环之前创建这些流。