java中如何通过套接字发送和接收对象
这是我的服务器类,我想发送简单的类“heee”,但每次连接到客户端时,我都会从try-catch中得到“users-wasnotsent”。我做错了什么java中如何通过套接字发送和接收对象,java,multithreading,Java,Multithreading,这是我的服务器类,我想发送简单的类“heee”,但每次连接到客户端时,我都会从try-catch中得到“users-wasnotsent”。我做错了什么 public class heee{ String me = "hehehe"; } public static void main(String args[]) throws Exception { ServerSocket ssock = new ServerSocket(2222); System.out.printl
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 Serializable,并添加了一个catch,在客户端,它告诉我在服务器的第43行(即run()处)中止写入方法这是异常java.io.WriteAbortedException的第一行:写入中止;java.io.NotSerializableException:MultiThreadedServer
和最后一行由以下原因引起:java.io.NotSerializableException:MultiThreadedServer',其中在服务器端它告诉我“java.io.NotSerializableException:MultiThreadedServer at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
并继续这样,如果您使两个heee
类都可序列化
,则不必删除此异常。