shahbinit
shahbinit

Reputation: 47

java.io.NotSerializableException:: ObjectOutputStream: writeObject method

I am trying to connect client to a server using sockets.

Server code:

ServerSocket server = new ServerSocket(6780);
Socket clientSocket = server.accept();
ObjectInputStream fromClient= new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream toClient = new ObjectOutputStream(clientSocket.getOutputStream());

Client code:

Socket nodeSocket = new Socket(ServerIP, 6780);
ObjectInputStream fromServer = new ObjectInputStream(nodeSocket.getInputStream());
ObjectOutputStream toServer = new ObjectOutputStream(nodeSocket.getOutputStream());
toServer.writeObject(this);

When a client connects, server listens and accepts client connection. But when I try to write my class object to the server, "toServer.writeObject(this);" it throws

java.io.NotSerializableException: Peer
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Peer.requestEntryNode(Peer.java:47)
at Peer.main(Peer.java:87)

Peer is my class name.

I tried to find out the cause of this exception, it says that object that needs to be written must be serializable. I also tried to implement Serializable interface from Peer class. But that doesnt help.

Can anyone suggest?

Upvotes: 1

Views: 11397

Answers (2)

shahbinit
shahbinit

Reputation: 47

Thanks all for the reply.

I found the solution. I made my Peer class to implement Serializable and those classes as well which were referenced from Peer class.

ObjectOutputStream and ObjectInputStream are not serialized. So I cannot make them class variables. I declared them local to each methods.

Works fine now.

Upvotes: 1

tmarwen
tmarwen

Reputation: 16354

Make sure that your class Peer and its dependencies do implement the java.io.Serializable interface:

import java.io.Serializable;

public class Peer implements Serializable {
  ...
}

Upvotes: 5

Related Questions