简体   繁体   English

无法将套接字流重用于其他数据类型? (Java)

[英]Cannot reuse socket stream for different data type? (Java)

I have a simple client server socket setup. 我有一个简单的客户端服务器套接字设置。

  1. Server accepts client connection. 服务器接受客户端连接。
  2. Server sends an object over the socket. 服务器通过套接字发送对象。
  3. Server does some calculations. 服务器进行一些计算。
  4. Over the same socket, server sends back a boolean value for whether the calculations were correct. 在同一套接字上,服务器返回一个布尔值,用于确定计算是否正确。 (this is where the thread freezes) (这是线程冻结的地方)

such that: 这样:

Server.java. Server.java。

connectionSocket = serverSocket.accept();
ObjectOutputStream objectStream = new ObjectOutputStream(connectionSocket.getOutputStream());

// first sends the object
objectStream.writeObject(testObject);

objectStream.flush(); // i dont really know
objectStream.reset();

// some code

// returns if the code was succesful
objectStream.writeBoolean(true);

Client.java 客户端.java

    // initial object sent over the socket
    object  = (TestObject) in.readObject();
    System.out.println(object.toString());

    // true if the server test was correct (thread freezes here)
    boolean b  = in.readBoolean();
    System.out.println("Test: " +b);
    clientSocket.close();

This is supposed to first return the 'testObject' print it's data to the screen and then return true and also print that to the screen. 应该首先返回“ testObject”,将其数据打印到屏幕上,然后返回true,然后将其打印到屏幕上。

However, it is able to do the first part, but freezes the thread at in.readBoolean(); 但是,它能够执行第一部分,但是将线程冻结在in.readBoolean();中。 I understand that streams hold a header holding data about the bytes sent, so my assumption was to call out.reset(); 我知道流包含一个头,其中包含有关所发送字节的数据,因此我的假设是调用out.reset();。 or out.flush(); 或out.flush(); but neither of these seem to do anything. 但这些似乎都不起作用。 I'm sure its a simple answer, but i can't find any examples of my exact problem. 我敢肯定,这是一个简单的答案,但我找不到确切问题的任何示例。

Cheers. 干杯。

Ahem.

Put flush after writeBoolean(); 在writeBoolean()之后放入同花顺

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM