开发者

reusing socket streams

I have a server socket that I setup, and a client socket that connects to the server socket.

In the following sequence:

  1. I open an ObjectOutputStream from the client to the server
  2. On the server I open an ObjectInputStream from the accepted socket connection from the client
  3. On the Server I open an ObjectOutputStream using the accepted socket connection from the client
  4. On the client I open an ObjectInputStream

Everything works without error. In a loop on the server I have the following

while(true) {
Map<Integer,Game> games = GameEngine.getGames();
System.out.println("Games is: " + games + " size is " + games.size());
secondaryOutputStream.writeObject(games);
secondaryOutputStream.flush();
// sleep for 2 seconds then send the games again
try {
    Thread.currentThread().sleep(4000);
} catch (InterruptedException ie) {
    ie.printStackTrace();
}

}

the secondaryOutputStream is the ObjectOutputStream from the server to the client. What I am doing here is writing a ma开发者_运维知识库p to the client. I do this repeatedly in a loop as you can see, using the same ObjectOutputStream.

There are no exceptions, so all the connections are sound. However, on the client side, I only receive the map once, after the socket connection is established with the server. If the map is updated and written to the client, I still see the original map values, when the server first wrote the map to the client. Can you reuse Object streams in this manner? Thanks indeed


ObjectOutputStream has a space saving (and identity preserving) feature where it keeps track of objects previously sent (based on object identity), and does not resend them. instead, it just sends a marker which indicates which object it previously sent, and the ObjectInputStream (which keeps a handle to all objects sent) just re-returns that object on the other end. you need to use ObjectOutputStream.reset() between each send so that the object will be completely resent. you can also use ObjectOutputStream.writeUnshared(), but this may not function exactly how you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜