套接字:即使建立连接,客户端也无法向服务器发送消息

时间:2019-04-07 11:20:01

标签: java sockets

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

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);
}
}
}

还有一个客户端类,该客户端类连接到服务器并发送String。

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();

}

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

1 个答案:

答案 0 :(得分:0)

您必须在ObjectInputStreams之前创建ObjectOutputStreams。

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