Reputation: 47
I am trying to make a small multiplayer game in Java. I got the tpc connection working, but for now i can only transmit strings. I would like to transmit more sophisticated data in packets, which would contain all the necessary data for synchronizing the game. Is it possible to transmit some kind of custom structures, or data from class instances in one tcp package? Or what would be a good way to do it(i googled but i couldn't find something that would fit my needs)?
Upvotes: 0
Views: 760
Reputation: 4600
I would like to transmit more sophisticated data in packets, which would contain all the necessary data for synchronizing the game.
If these data are Serializable
(for example, your data consists of only primitives, string and array of primitives or array of strings), then you can use some standard Collection
like Vector
, List
, Map
etc to hold your data. They are serializable (check their documentation). So what you need to just use this:
objectOutputStream.writeObject(data)
Assuming that you are using ObjectOutputStream
to send packets. But if you don't need to create your own custom data structure, you need to tag it with java.io.Serializable
, as others have pointed out.
NOTE: In a class that implements Serializable, you must ensure that every instance variable of that class is a Serializable type.
Upvotes: 0
Reputation: 33544
- If you are not satisfied with the plain String going across the socket, you can then Use Serialization
.
- Serialization
must be used when the same java program is used to write and read the data.
- Serialization
flattens and inflates the Object while storing and retrieving respectively.
- Its actually not the Object, but its Instance variables
are used saved and later used to resurrect an identical object on the heap....
Upvotes: 0
Reputation: 16035
The most basic, yet not optimal way is to use the Serializable-marker interface, see for example here: Discover the secrets of the Java Serialization API.
The better way is to use some binary protocol, see here for some examples: general-purpose binary protocols or cook your own.
Upvotes: 1
Reputation: 993871
In general, the keyword to look for here is serialization. That is the process of converting a data structure to a chunk of bytes that can be sent across a socket or other transmission medium.
One way to do this is to use the Google Protocol Buffers library, which has bindings for use with Java.
Upvotes: 2