简体   繁体   中英

Should sockets for TCP/IP etc. be kept in a separate class? (Java)

I don't think I need to post my code (there's lots of it) but I'm happy to if prompted.

I am creating a distributed racing game in Java which currently has JFrame, JPanel and Car classes. I'm seeking the best way to implement the next stage which is the distributed part - I'm using TCP/IP rather than UDP as this is basically part of the requirements so there's no need to comment on that.

So I'm questioning client and server sockets, streams and buffered readers etc.

For, I guess you could say, best practice - I'm wondering if I should start the implementation by having it all separate from main for elegance and possibly extensibility etc.

In general you are looking to use OO for separation of concerns. This means you divide what needs to be done in several manageable chunks. Then you decide on a clean understandable interface for each chunk, which hides the implementation details that aren't relevant to the user of the class.

In your case the reasoning could go something like this ( but it is entirely up to the problem you have).

  1. One class is handling the connecting/disconnecting and returns an simple object that represents a message sent or received. This class knows nothing or little about the contents sent over the line, but it knows how to set up a connection and what to do with a disconnect.
  2. The next class in line converts the simple message objects to useful objects with convenience methods that are easy to handle.
  3. Another class is responsible for putting these objects to effect.

Of course when one of these tasks gets too big you can split them up even further.

In most cases this will result in one object managing one socket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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