umerk44
umerk44

Reputation: 2817

Java socket, Is that a dead lock or what?

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

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

Upvotes: 4

Views: 1456

Answers (2)

user207421
user207421

Reputation: 311039

It's not a deadlock, just bad code. You keep calling readUTF() and then throwing the result away and calling it again, as though the same thing was being sent as many times as you are calling it, which it isn't. So you are blocking, in the redundant calls to readUTF().

So don't do that. Call it once and store the result in a variable.

And it will never return null. Check the Javadoc.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533820

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

Upvotes: 2

Related Questions