简体   繁体   English

读写Java套接字而不会阻塞

[英]Read and write java socket without blocking

I have a simple Java IO TCP server/client protoype, where the server is writing heavily to the client, and the client writes occasionally to the server. 我有一个简单的Java IO TCP服务器/客户端原型,其中服务器正在向客户端大量写入数据,而客户端偶尔会向服务器写入数据。 Writing occurs a while loop, particularly in the run() method of a Worker thread, as is standard: 写入发生while循环,尤其是在标准的Worker线程的run()方法中:

@Override
public void run() {
    while (true) {
        // Server writes to client
        try {
            socket.getOutputStream.write(writeArray);
        } catch (Exception e) {
            System.exit(1);
        }
}

This is in a while loop, so if I also included a read operation, it would block. 这是在while循环中,所以如果我还包括读取操作,它将阻塞。

@Override
public void run() {
    while (true) {
        // Server writes to client
        try {
            socket.getOutputStream.write(writeArray);
        } catch (Exception e) {
            System.exit(1);
        }

        // Server reads from client
        try {
            int read = socket.getInputStream.read();
        } catch (Exception e) {
            System.exit(1);
        }
}

Is there a standard pattern on how to allow for occasional reads without blocking or heavily wasting CPU cycles? 关于如何允许偶尔读取而不会阻塞或严重浪费CPU周期的标准模式吗?

Take a look at the available() method: https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#available-- . 看一下available()方法: https : //docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#available-- Then you only need to read "if available". 然后,您只需阅读“如果可用”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM