James
James

Reputation: 223

How can I send an instance over a socket connection?

I'm attempting to write two Java programs. One to simulate a server, and one to simulate a client.

How could I go about sending an instance of a Response class over a socket?

The Response class represents status codes of the server connection. e.g. 404 Not Found etc

I'm not allowed to use Serialisation unfortunately.

Any advice would be greatly appreciated.

Upvotes: 1

Views: 371

Answers (2)

Deadron
Deadron

Reputation: 5289

At some level Serialization must occur in order to send an object across a connection. I can only assume your comment about being not allowed to use serialization refers to not being able to use Serializable instead of a blanket prohibition of serialization(which makes no sense). A very simple method to accomplish this would be the use of a external serialization library such as gson. Gson serializes an object into a JSON string that you can transmit over your socket and then using the same library deserialize it back into an object on the other side. You can of course use any of your preferred serialization libraries with your favorite format eg. XML, json, YAML,...

Upvotes: 3

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

You wouldn't be sending an instance of the Response class itself. When sending things over a network, client and server machines understand bytes. Your application can understand more than bytes, it can understand specific representations. For example, your server might send a JSON representation of your Response class like:

{
   "response" : {
       "code":404
   }
}

Then your client must be able to understand what this sequence of bytes means. That's basically what a protocol is: how two machines can communicate.

Regardless of what language the server or clients are written in, the Response is an Entity. In Java you might use a Class to represent it, in C++ you might use a struct. However, both would need to know that when you are communicating with an external application.system, they would have to put it in a format that everyone understands, be it json, xml, or any other.

As for sending this through sockets, Oracle has a nice tutorial here. You get the OutputStream from the socket and start writing your representation.

Upvotes: 1

Related Questions