首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java死锁问题

问Java死锁问题
EN

Stack Overflow用户
提问于 2010-05-09 16:41:02
回答 1查看 2.7K关注 0票数 3

我正在使用java套接字进行通信。在客户端,我有一些处理,在这一点上,我将一个对象发送到send。代码如下:

代码语言:javascript
复制
while (true) {
  try {
    Socket server = new Socket("localhost", 3000);
    OutputStream os = server.getOutputStream();
    InputStream is = server.getInputStream();

    CommMessage commMessage = new CommMessageImpl();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(commMessage);
    os.write(bos.toByteArray());
    os.flush();

    byte[] buff = new byte[512];
    int bytesRead = 0;
    ByteArrayOutputStream receivedObject = new ByteArrayOutputStream();
    while ((bytesRead = is.read(buff)) > -1) {
      receivedObject.write(buff, 0, bytesRead);
      System.out.println(receivedObject);
    }
    os.close();
    Thread.sleep(10000);
  } catch (IOException e) {
  } catch (InterruptedException e) {
  }
}

接下来,在服务器端,我使用以下代码读取对象并写入响应(这只是一个回显消息)。

代码语言:javascript
复制
public void startServer() {
  Socket client = null;
  try {
    server = new ServerSocket(3000);
    logger.log(Level.INFO, "Waiting for connections.");
    client = server.accept();
    logger.log(Level.INFO, "Accepted a connection from: " + client.getInetAddress());
    os = new ObjectOutputStream(client.getOutputStream());
    is = new ObjectInputStream(client.getInputStream());

    // Read contents of the stream and store it into a byte array.
    byte[] buff = new byte[512];
    int bytesRead = 0;
    ByteArrayOutputStream receivedObject = new ByteArrayOutputStream();
    while ((bytesRead = is.read(buff)) > -1) {
      receivedObject.write(buff, 0, bytesRead);
    }

    // Check if received stream is CommMessage or not contents.
    CommMessage commMessage = getCommMessage(receivedObject);
    if (commMessage != null) {
      commMessage.setSessionState(this.sessionManager.getState().getState());
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream oos = new ObjectOutputStream(bos);
      oos.writeObject(commMessage);
      os.write(bos.toByteArray());
      System.out.println(commMessage.getCommMessageType());
    } else {
      processData(receivedObject, this.sessionManager);
    }
    os.flush();
    } catch (IOException e) {
    } finally {
      try {
        is.close();
        os.close();
        client.close();
        server.close();
      } catch (IOException e) {
    }
  }
}

如果我不尝试在客户端读取数据(如果我排除了与读取相关的代码),上面的代码就可以正常工作。但是如果我有这段代码,出于某种原因,我在访问输入流时会遇到某种死锁。你知道我可能做错了什么吗?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-05-09 16:56:46

客户端和服务器都试图读取整个输入流(即直到EOF的所有内容),但都没有发送EOF(通过调用套接字上的shutdownOutput() )。

为什么需要将对象数据临时存储在ByteArrayOutputStream中?如果直接从套接字输入流读取,这可能更容易修复。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2797087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档