3

I was attempting to communicate to a device server with Sockets, after having my little Java program hang when on readLine I ended up having to inject my target application with a packet sniffer and found out that os.writeBytes("notify\n"); was being split to two packets, the first containing n and the next otify, of which the server did not like. I fixed this by adding another writeBytes before hand:

os.writeBytes(" ");
os.writeBytes("notify\n");
os.flush();

This to me seems a bit hacky and potentially unstable, could someone shed some light why I'm having to do this and give me a better solution.

Cheers

3
  • TCP sockets, or something else?
    – Mat
    Commented May 14, 2012 at 17:36
  • Is there a reason you're using writeBytes instead of a different flavor of write?
    – Thomas
    Commented May 14, 2012 at 17:37
  • If you're sending the string over a TCP connection I can't think of a reason why this would cause problems since TCP provides a data communications stream. Try flushing the output stream (os.flush()) after writing the string.
    – smichak
    Commented May 14, 2012 at 17:39

1 Answer 1

2

When working with raw socket connections, you can never assume that you will get your messages in discrete chunks. In a production environment, its entirely possible you will receive partial messages, or multiple messages at a time.

If you don't want to deal with this, you should consider using a library like Netty which handles these concerns for the programmer.

Having said that, I agree with Thomas that your problem is probably related to your choice of writeBytes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.