0

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);
}
}
2
  • Please post definition of Server class Commented Oct 1, 2015 at 23:32
  • Your read loop is invalid. client.isClosed() doesn't magically become true when the peer disconnects, and readObject() doesn't return null unless you wrote a null. You should loop until EOFException is caught. Commented Oct 6, 2015 at 3:09

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.