我有一个通过socket连接的客户端/服务器。
客户端写入要由服务器读取的整数值
我在readInt()
中使用ObjectOutputStream
来写入此值
在服务器端,我使用readInt()
中的ObjectInputStream
来读取此值。
但服务器没有读任何内容,它冻结在readInt()
使用ObjectInputStream
阅读时出现什么问题?
我使用DataOutputStream
,读写成功,但ObjectInputstream
可以读取整数和其他原始类型,有什么问题?
public class Server {
ServerSocket listener;
private static final int PORT = 9001;
private Socket socket;
private ObjectInputStream obin = null;
private ObjectOutputStream obout = null;
public Server() throws Exception{
listener = new ServerSocket(PORT);
run();
}
public void run() throws Exception{
socket = listener.accept();
obout = new ObjectOutputStream(socket.getOutputStream());
obout.flush();
obin = new ObjectInputStream(socket.getInputStream());
int h=obin.readInt();
System.out.println(h);
obout.writeInt(77);
}
public static void main(String[] args) throws Exception {
Server s = new Server();
}
}
和客户
public class Client {
private ObjectInputStream oin = null;
private ObjectOutputStream oot = null;
private Socket socket = null;
public Client() throws Exception{
String serverAddress = "127.0.0.1";
socket = new Socket(serverAddress, 9001);
oot = new ObjectOutputStream(socket.getOutputStream());
oot.flush();
oin = new ObjectInputStream(socket.getInputStream());
oot.writeInt(66);
int u = oin.readInt();
System.out.println(u);
}
public static void main(String[] args) throws Exception{
Client c= new Client();
}
}
当你运行这个代码时应该到达服务器66 在客户端77, 但实际上我什么都没得到。为什么呢?
答案 0 :(得分:1)
每次写入后都应该刷新(),因为它会清除通过网络发送字节的输出缓冲区。所以你的服务器运行方法应该是:
public void run() throws Exception {
socket = listener.accept();
obin = new ObjectInputStream(socket.getInputStream());
int h = obin.readInt();
System.out.println(h);
obout = new ObjectOutputStream(socket.getOutputStream());
obout.writeInt(77);
obout.flush();
}
和您的客户端构造函数:
public Client() throws Exception {
String serverAddress = "127.0.0.1";
socket = new Socket(serverAddress, 9001);
oot = new ObjectOutputStream(socket.getOutputStream());
oot.writeInt(66);
oot.flush();
oin = new ObjectInputStream(socket.getInputStream());
int u = oin.readInt();
System.out.println(u);
}
如果您将此作为练习,那很好,但如果您要在生产中运行基于此的代码,请考虑使用更高级别的网络库,如protocol buffers。