gpt4 book ai didi

java - 套接字编程: Input Stream seems to block Output Stream

转载 作者:行者123 更新时间:2023-11-30 05:05:10 25 4
gpt4 key购买 nike

我正在尝试编写一个服务器-客户端通信应用程序,该应用程序使用两个单独的线程,一个用于输入,一个用于输出。不过,我遇到了一个奇怪的“死锁”问题:当一个线程读取输入,但客户端没有发送任何内容时,该线程将停止(因为它正在等待输入)。但是,由于某种原因,当输入线程被阻塞时,输出线程无法写入任何内容。

此代码示例对此进行了说明:

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;

public class TestServer {
public static void main(String... args) throws IOException {

/* Creates a server socket that lurks about our port waiting for connections */
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(4114));


while(true){
SocketChannel connectionChannel = serverChannel.accept();
if(connectionChannel != null){
final Socket connection = connectionChannel.socket();


new Thread(){
public void run(){
try {
System.out.println("READING");
System.out.flush();
// If the next line is commented out, nothing blocks
connection.getInputStream().read();
System.out.println("DONE READING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();

new Thread(){
public void run(){
try {
System.out.println("WRITING");
System.out.flush();
new DataOutputStream(connection.getOutputStream()).writeBytes("AUGH!!!");
//connection.getOutputStream().write(5);
System.out.println("DONE WRITING");
System.out.flush();
} catch (Exception e){
e.printStackTrace();
}
}
}.start();

break;
}
}
}
}

客户端代码:

import java.net.*;
import java.io.*;

public class TestClient {

public static void main(String... args) throws IOException {
Socket connection = new Socket("127.0.0.1", 4114);
while(true){
System.out.println(connection.getInputStream().read());
}
}

}

上面的代码示例会阻塞,但如果服务器中的行被注释掉,则不会阻塞。这是为什么?套接字是否仅限于同时等待输入/输出?这是怎么回事?

最佳答案

我不确定您为什么会看到这个,但这与使用 channel 有关。

如果将此代码替换为

ServerSocket ss = new ServerSocket(4114);
Socket connection = ss.accept();

它会按照你想要的方式工作。

关于java - 套接字编程: Input Stream seems to block Output Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com