Why do I get "java.io.NotSerializableException: java.net.Socket"?
I was testing out the ObjectOutputStream class; my code was practically copied word for word from the tutorial, but when I run it, I get
"java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.net.Socket"
These are my classes. I made my TestObject class serializable, so I don't understand why I'm getting the error. I wanted to make a class that would serve as a link between the server and the client: the server would add the clients to TestObject, and the TestObject would give itself to the client. Then the TestObject would handle all the communication. I'm just starting the networking tutorials, so I apologize if I'm just being stupid with this one.
Code:
public class GameServer
{
public static void main(String args[]) throws IOException
{
ServerSocket ss = new ServerSocket(4117);
TestObject obj = new TestObject();
Thread t = new Thread(obj);
t.start();
System.out.println("Waiting for clients...");
while(true)
{
Socket s = ss.accept();
System.out.println("Client Connected");
obj.addClient(s);
}
}
}
public class TestObject implements Runnable, Serializable
{
private ArrayList<Socket> clients;
public TestObject()
{
clients = new ArrayList<Socket>();
}
public void addClient(Socket s) throws IOException
{
clients.add(s);
OutputStream out = s.getOutputStream();
ObjectOutputStream outos = new ObjectOutputStream(out);
outos.writeObject(this);
}
}
public class GameClient implements Serializable
{
public static void main(String args[]) throws ClassNotFoundException
{
try
{
Socket s = new Socket("localhost", 4117);
InputStream is = s.getInputStream();
ObjectInputStream os = new ObjectInputStream(is);
TestObject obj = (TestObject)os.readObject();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}