Is it possible to send an object using Sockets, if so, how
it can be?

Answer Posted / roshan tiwari btech cs agra

Objects that implement Serializable may be sent across a socket connection using an ObjectInputStream and ObjectOutputStream combination.

Here are the steps to follow:

First, define an object to send. As an example, we can define a class called Message to encapsulate our communications:
public class Message implements Serializable {
private int senderID;
private String messageText;

public Message(int id, String text) {
senderID = id;
messageText = text;
}
public String getText() {
return messageText;
}
}
Next, instantiate the object, wrap the socket's streams in object streams, then send the message across the socket:
Message sayhey = new Message("123456789", "Hello");

Socket socket = new Socket(host, port);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());

out.writeObject(sayhey);
On the other side of the socket, the message can be retrieved and used by invoking methods on the returned object:
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Message messageObject = (Message) in.readObject();
String messageText = messageObject.getText();

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Explain look for local ports?

831


What are the advantages and disadvantages of sockets?

776


To create a socket, you need to know the internet host to which you want to connect?

747


What is an http redirector?

718


What is the use of network interface?

684


What is an http server?

756


What is jhttp web server?

974


What is a listener in networking?

807


What is cookies in networking ?

810


Why socketutil is used?

810


What is the Difference between socket and servlet?

1028


How we can make simple java program for Server/Client Communication

854


What is a thread pool?

833


If you do not want your program to halt while it waits for a connection, put the call to accept( ) in a separate thread?

733


What do you understand by the term network?

761