java.io和socket.getInputStream()

gre*_*her 1 java sockets java-io

我有这个代码:

 Socket incomingConnection = serverSocket.accept();
 String strategy = "1";
 Client client = new Client(incomingConnection, this, strategy);
Run Code Online (Sandbox Code Playgroud)

客户构造函数:

  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();
    }
Run Code Online (Sandbox Code Playgroud)

现在看起来像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());
}
Run Code Online (Sandbox Code Playgroud)

战略2一样. 客户端类中的方法:

client.getInputStream() {
    return inputStream;
}
// similar for outputStream
Run Code Online (Sandbox Code Playgroud)

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

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

为什么?

jop*_*jop 5

交换这些行:

inputStream = new ObjectInputStream(client.getInputStream());
outputStream = new ObjectOutputStream(client.getOutputStream());
Run Code Online (Sandbox Code Playgroud)

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