Lucas Baizer
Lucas Baizer

Reputation: 199

Java "NotSerializableException: java.net.Socket" When Not Sending A Socket

So I send a Server object to a client with this thread:

public ConnectionThread(final Server server) {
    super(new Runnable() {
        public void run() {
            try {
                Socket client = server.serverSocket.accept();
                server.clients.add(client);

                ObjectInputStream in = new ObjectInputStream(
                        client.getInputStream());
                ObjectOutputStream out = new ObjectOutputStream(
                        client.getOutputStream());

                System.out.println("Connected client: "
                        + client.getRemoteSocketAddress());
                server.launchNewThread();

                Object input;
                while (!client.isClosed()) {
                    input = in.readObject();

                    if (input != null) {
                        if (input.toString().equals("server")) {
                            out.writeObject(server);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

And when I call out.writeObject(server) I get this exception:

java.io.NotSerializableException: java.net.Socket

Here is the Server class:

public class Server implements Serializable {
private static final long serialVersionUID = 4634111951586948020L;

public ServerArgs args;

public ArrayList<Socket> clients = new ArrayList<Socket>();
public ServerSocket serverSocket;

public Server(int port) throws IOException {
    serverSocket = new ServerSocket(port);

    launchNewThread();
}

public void launchNewThread() {
    ConnectionThread thread = new ConnectionThread(this);
    thread.start();
}

public static void main(String[] args) throws IOException {
    new Server(27015);
}
}

Upvotes: 0

Views: 856

Answers (1)

public ArrayList<Socket> clients = new ArrayList<Socket>();
public ServerSocket serverSocket;

You have plenty of non-serializable sockets right there. It's very unclear what the purpose of "sending a server" is, but perhaps you should either just send the ServerArgs or mark those two fields transient.

Upvotes: 2

Related Questions