java.io 和 socket.getInputStream()

标签 java sockets java-io

我有这个代码:

 Socket incomingConnection = serverSocket.accept();
 String strategy = "1";
 Client client = new Client(incomingConnection, this, strategy);

客户端构造函数:

  public Client(Socket socket, ChatServer chatServer, String strategy) throws IOException{
        this.socket = socket;
        this.inputStream = socket.getInputStream();
        this.outputStream = socket.getOutputStream();

        this.chatServer = chatServer;
        this.instance1 = new Strategy1(chatServer, this);
        this.instance2 = new Strategy2(chatServer, this);
        this.strategy = (this.instance1.getName().equals(strategy1) ? this.instance1 : this.instance2);
        this.strategy.setStreams();
    }

现在看起来像Strategy1:

public class Strategy1{
public Strategy1(ChatServer server, Client client) throws IOException{
    this.chatServer = server;
    this.client = client;
}

public void setStreams() throws IOException{
    inputStream = new ObjectInputStream(client.getInputStream());
    outputStream = new ObjectOutputStream(client.getOutputStream());
}

同样的Strategy2客户端类中的方法:

client.getInputStream() {
    return inputStream;
}
// similar for outputStream

问题是:当 Client 的构造函数尝试执行 strategy.setStreams() 时,程序会在 new ObjectInputStream() 上阻塞.

当我将 setStream() 方法的包含移动到 Strategy1 的构造函数中时,它就可以工作了!

为什么?

最佳答案

交换这些行:

inputStream = new ObjectInputStream(client.getInputStream());
outputStream = new ObjectOutputStream(client.getOutputStream());

创建一个 ObjectInputStream 从套接字读取。如果您首先在连接的两端创建输入流,它将死锁。最安全的方法是始终先创建输出流。

关于java.io 和 socket.getInputStream(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17025432/

相关文章:

java - SQLite:如何插入未完整填充列的文档?

c - Unix 套接字 C : Connecting from another network

c - 套接字操作上的非套接字错误

java - 使用Java读取路径中带有空格的文件

java - 需要 pdf 渲染器的帮助

java - 在没有 ArgumentCaptor 的情况下匹配可变对象

java - Android : com. google.maps :google-maps-services:0. 1.7 给出构建错误

java - 使用哪种布局?

c - tcp 服务器阻塞读取 C

Java路径: Build and absolute path