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;
}
}
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.
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.
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 ....
}
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.
精彩评论