java套接字连接阻塞过程

时间:2013-09-25 16:17:04

标签: java sockets

我正在使用两个使用套接字进行通信的java进程。

从服务器端,我用它来发送信息:

public void send(Serializable order)
{
    try
    {
        if (this.clientSocket != null && this.clientSocket.isBound() && this.clientSocket.isConnected())
        {
            String json = "";
            json = mapper.writeValueAsString(order);
            log.info("sending to client : " + order.getClass());

            json = convertToUTF8(json);

            this.output.write(json + "\n");
            this.output.flush();
            log.info("Message sent to client");
        }
        else
        {
            log.info("no client connected");
        }
    }
    catch (Exception e)
    {
        log.fatal("Exception while trying to send message to client : " + e.getMessage(), e);
    }
}

这里的输出是:

private BufferedWriter output;

在客户端,我尝试读取这样的数据:

while (this.running)
        {   
            try
            {
                String msg = in.readLine();

                log.debug("MSG VALUE IS : |"+msg+"|\n\n**********\n");

                if ("".equalsIgnoreCase(msg) || msg == null)
                {
                    break;
                }

这里是:

private BufferedReader in;

这里的问题是在一段时间后,服务器进程被阻止,如果我运行netstat命令,我可以看到recv-Q和send-Q值不是0。

但是我无法重现自己的情况,所以我想知道是什么产生了这种情况,还有办法解决这个问题,还是我必须改变读取数据的方式?

提前致谢。

2 个答案:

答案 0 :(得分:0)

通常,如果您在服务器端代码中使用阻塞IO操作,则每个客户端都需要拥有自己的工作线程,负责发送到该客户端。

另一种选择是使用NIO(或某些使用NIO的框架)来允许服务器复用内容。

答案 1 :(得分:0)

为避免阻止,您应该使用每次请求。

非常简短的例子:

public class App {


    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = null; // consider it is properly initialized

        while (true /* stub health condition */) {

            Socket clientSocket = serverSocket.accept(); // the blocking call
            final Worker worker = new Worker(clientSocket);

            Thread workerThread = new Thread() {

                @Override
                public void run() {
                    // handle request here
                    worker.send(new Serializable(){} /* stub */);
                }

            };

            workerThread.start();
        }

    }


}

class Worker {

    private Socket clientSocket;

    Worker (Socket clientSocket) {
        this.clientSocket = clientSocket;
    }

    public void send(Serializable order) {
        // logic
    }

}