Rami
Rami

Reputation: 2148

Serializing socket

I tried serializing socket but it didn't work. what is the proper way ?

public class MySocket implements Serializable
{
    private Socket socket;

    public MySocket(Socket socket) {
        this.socket = socket;

    }
    public Socket getSocket() {
        return socket;
    }
    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}

Upvotes: 2

Views: 6220

Answers (4)

av1987
av1987

Reputation: 493

Well, In socket programming when you say serialize that means the object should be "serializable" not the socket it self.

inSomeclass's method {
     ...
     ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
     out.writeObject(new MyClass());
     out.flush();
     ...
}

class MyClass implements Serializable {
     // some sort of variables and objects, whatever ....
} 

Upvotes: 1

user814168
user814168

Reputation: 131

Socket basically is a file descriptor on the system level, similar to a file. It's just an integer. It can be serialized but it doesn't make sense to do so. When a socket is closed, the file descriptor no long makes sense. It also doesn't make sense if you use it on another machine.

Upvotes: 1

Shamit Verma
Shamit Verma

Reputation: 3827

This would not work since a member variable "socket" is not serializable.

Do you want to serialize something over a socket? In that case the class that has data should be serialized not the one that is handling sockets.

Upvotes: 0

user7094
user7094

Reputation:

By design Socket instances are not serializable - you cannot save them or transmit them over a network, that wouldn't make any sense. Depending on what you're trying to do, you need to establish a new socket each time you need one rather than saving it to disk etc.

Upvotes: 9

Related Questions