java - 套接字:即使建立连接,客户端也无法向服务器发送消息
问题描述
我有一个监听新连接的服务器类:
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();
}
当我运行服务器时,它开始监听连接,然后我启动客户端。连接正常建立,但未发送字符串。怎么了?
解决方案
您必须在 ObjectInputStreams 之前创建 ObjectOutputStreams。
创建 ObjectInput- 或 ObjectOutputStream 时,会读取/写入序列化流标头。因为您是在 OutputStream 之前在客户端和服务器上创建 ObjectInputStream,所以它们都阻止尝试读取标头,该标头尚不可用。
推荐阅读
- regex - 添加到正则表达式模式,因此字符串可能不包含句点
- html - 如何使用 flexdashboard 添加指向徽标的链接?
- angular - ngx-leaflet 在 Dropbox 选择的值更改后重新加载地图
- java - Spring Security 登录页面 url 参数
- reset - AOG 隐式帐户链接 - 如何重置?
- java - Springboot 503 服务不可用
- java - HMAC解密
- html - 在移动版中将菜单居中,但在桌面版中不居中
- r - 将来自 Fisher 测试的多个 p 值合并到原始数据
- c++ - 如何使用 C++ 将一个字符串替换为 csv 文件中的另一个字符串