繁体   English   中英

通过对象流读写

[英]Read and write via Object Stream

我有一个通过套接字连接的客户端/服务器。 客户端写入要由服务器读取的整数值,我在ObjectOutputStream使用readInt()写入此值,而在服务器端,我在ObjectInputStream使用readInt()读取此值。 但是服务器没有读取任何内容,而是冻结在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上获取代码,但是实际上我什么也没得到。 为什么?

每次写完后,您应该使用flush()清除输出缓冲区,该缓冲区通过网络发送字节。 因此,您的服务器运行方法应为:

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

如果您是在做练习,那很好,但是如果要在生产环境中运行基于此的代码,请考虑使用更高级别的网络库,例如协议缓冲区

暂无
暂无

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

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