繁体   English   中英

如何通过Java中的套接字发送和接收对象

[英]how to send and receive object through sockets in java

这是我的服务器类,我想发送简单的类“ heee”,但是每次我连接到客户端时,都会从try catch中获取“未发送用户”。 我究竟做错了什么?

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签名中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM