Java套接字,那是死锁还是什么?

2022-01-19 00:00:00 sockets network-programming java

我有一个在服务器端使用套接字的客户端-服务器程序,并且读写是以这种方式发生的

I have a client-server program using socket on the server side and read and write is happening in that way

soc = serversocket.accept();
System.out.println("Accepted");

in = new ObjectInputStream(soc.getInputStream());
out = new ObjectOutputStream(soc.getOutputStream());

if(in.readUTF() == null ? " " != null : !in.readUTF().equals(" "))
{
    diskinfo.setPath(in.readUTF());
}
Item[] pac = diskinfo.get();

out.writeObject(pac);

同样在 cilent(android) 方面...

and similarly on the cilent(android) side...

Log.v("read", "item");
soc = new Socket(InetAddress.getByName("10.0.2.2"), 3838);
output = new ObjectOutputStream(soc.getOutputStream());
input = new ObjectInputStream(soc.getInputStream());

try 
{
    output.writeUTF(path);
    packets = (Item[]) input.readObject();
} 
catch (ClassNotFoundException e) 
{
    // TODO Auto-generated catch block
    e.printStackTrace();
}

问题是,连接建立后程序卡住了,不报错也不例外;停下来

The problem is that, after the connection is established the program stuck their, giving no error no exception; just stop

推荐答案

这是一个死锁,你必须先创建并刷新 ObjectOutputStream.这是因为 ObjectInputStream 在继续之前会读取 OOS 发送的 header.

Its a deadlock, you must create and flush the ObjectOutputStream first. This is because ObjectInputStream reads the header sent by the OOS before continuing.

相关文章