簡體   English   中英

java套接字連接阻塞過程

[英]java socket connection blocking process

我正在使用通過套接字進行通信的兩個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。

但是我無法重現這種情況,所以我想知道是什么導致了這種情況,這是一種處理這種情況的方法,還是我必須更改讀取數據的方式?

提前致謝。

通常,如果您使用的是從服務器端代碼阻止IO操作,則每個客戶端都需要擁有自己的工作線程,該線程負責發送給該客戶端。

另一個選擇是使用NIO(或某些使用NIO的框架)來允許您的服務器多路復用。

為了避免阻塞,您應該使用“每請求一個廣告”。

非常簡單的例子:

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
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM