首页 > 解决方案 > 套接字:即使建立连接,客户端也无法向服务器发送消息

问题描述

我有一个监听新连接的服务器类:

public class Server{
public static void main(String[] args){
ServerSocket ss = new ServerSocket(port);
System.out.println(" Listening for connections");
String typeOfConnection;
Socket s = null;
try {
      // socket object to receive incoming client requests
      s = ss.accept();


      // obtaining input and out streams
      ObjectInputStream dis = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream dos = new ObjectOutputStream(s.getOutputStream());

      typeOfConnection = dis.readUTF();   //Read a message with the type of client that wants to connect (publisher or subscriber)
      System.out.println(typeOfConnection);
}
}
}

还有一个客户端类,它连接到服务器并发送一个字符串。

public class Client{
    public static void main(String[] args){
         InetAddress ip = InetAddress.getByName("//myIp")
         Socket s = new Socket(ip, 3201)

         ObjectInputStream dis = new ObjectInputStream(s.getInputStream())
                  ObjectOutputStream dos = new ObjectOutputStream(s.getOutputStream())

         dos.writeUTF("Hi");
         dos.flush();

}

当我运行服务器时,它开始监听连接,然后我启动客户端。连接正常建立,但未发送字符串。怎么了?

标签: javasockets

解决方案


您必须在 ObjectInputStreams 之前创建 ObjectOutputStreams。

创建 ObjectInput- 或 ObjectOutputStream 时,会读取/写入序列化流标头。因为您是在 OutputStream 之前在客户端和服务器上创建 ObjectInputStream,所以它们都阻止尝试读取标头,该标头尚不可用。


推荐阅读