I’ve started work on a simple newtworking project which creates a new thread for each connection and I’m trying to send multiple things across. What I’m wondering is there an easy way of simple say declaring a variable sending that whole variable to the server and that being sent to other clients. For example if I wanted to send a simple integer array? Basically how would I send an array or even an image across a socket?
Share
Yes, it is possible. What you are looking for is called serialization and can be used to send entire objects through a stream (socket, file, etc.). Have a look at this java socket serialization tutorial.
Check the docs on ObjectOutpuStream and ObjectInputStream.
Basically what you have to do is have any custom type that you want to be serialized implement the
Serializableinterface:This is a marker interface that tells the runtime that this type can be sent over a stream.
Next, once your connections are set up you can obtain the socket input/output stream and write objects using
ObjectOutputStream:or read them using
ObjectInputStream:(
clientabove is aSocket).