【问题标题】:java.io and socket.getInputStream()java.io 和 socket.getInputStream()
【发布时间】:2013-06-06 04:48:31
【问题描述】:

我有这个代码:

 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 的构造函数中时,它就可以工作了!

为什么?

【问题讨论】:

    标签: java sockets java-io


    【解决方案1】:

    交换这些行:

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

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

    【讨论】:

      猜你喜欢
      • 2014-01-31
      • 2012-01-12
      • 1970-01-01
      • 2020-09-12
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      相关资源
      最近更新 更多