如何通过java中的套接字发送和接收对象
这里是我的服务器类,我想发送简单的类'heee',但每次连接到客户端时,我都会从try catch获取'用户未发送'。我究竟做错了什么?如何通过java中的套接字发送和接收对象
public class heee{
String me = "hehehe";
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(2222);
System.out.println("Listening");
while (true)
{
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadedServer(sock)).start();
}
}
@Override
public void run() {
try
{
out = new ObjectOutputStream(csocket.getOutputStream());
heee hope = new heee();
out.writeObject(hope);
System.out.println("debug line");
}catch(Exception ex)
{
System.out.println("users was not sent");
}
这里我想读取线程中的对象。
public class ChatServer implements Runnable {
Socket clientSocket = null;
ObjectInputStream in = null;
@Override
public void run()
{
try
{
clientSocket = new Socket ("localhost", 2222);
in = new ObjectInputStream(clientSocket.getInputStream());
heee nope = (heee) in.readObject();
System.out.print(nope.me);
} catch(Exception Ex)
{
}
}
public static void main(String args[]) throws Exception {
new Thread(new ChatServer()).start();
}
public class heee{
String me;
}
}
如果您想查看错误的真实原因,则需要打印堆栈跟踪。你赶上NotSerializableException
。每个想要写入或读取的对象都必须是可序列化的。将implement Serializable
添加到heee
签名。
好的我已经在这两个文件中使heee可序列化并添加了一个catch,并且在客户端它告诉我写入在服务器的第43行是run()方法中止,这是异常的第一行' java.io.WriteAbortedException:写入中止; java.io.NotSerializableException:MultiThreadedServer'和最后一行'由...引发:java.io.NotSerializableException:MultiThreadedServer'在服务器端,它告诉我java.io.NotSerializableException:MultiThreadedServer在java.io.ObjectOutputStream处为 \t。 writeObject0(ObjectOutputStream.java:1184)',并继续如此 – Peter
如果你把两个'heee'类'Serializable'都做了,这个例外就不一定了。 –
现在起作用了,我把课程结构搞砸了 – Peter
“我做错了什么?”您不打印异常。 – tkausl