Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comunication with a device through a socket  RSS feed

 
E. Domenech
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

i am usually a delphi developer and I don't have too much experience with java. We are starting using java in this project.

I have to develop a software that communicates with a device through a socket. The device sends a sequence of bytes that looks like
this 0x7E CMD NUMBEROFBYTEMS DATA CRC 0x81 and once i get the sequence i have to send a sequence like this to the device
0x7E 0x30 0x00 0x00 0x30 0x81.

This is the code of the method i use to listen to the socket:


My problem is that i never get out of the loop, if i change the condition of the loop to ((c = in.read()) != x81) it works but i don't
know if it's the right thing to do since i don't get the last byte of the sequence. Are DataInputStream and DataOutputStream
the right kind of stream to use?

Thank you in advance.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Domenech wrote:My problem is that i never get out of the loop, if i change the condition of the loop to ((c = in.read()) != x81) it works but i don't
know if it's the right thing to do since i don't get the last byte of the sequence.

Use a break statement inside the loop:
Are DataInputStream and DataOutputStream the right kind of stream to use?

You probably don't need DataInputStream/DataOutputStream. Regular InputStream/OutputStream is probably good enough.

You do have one major flaw in your code:
That line does not send a sequence of bytes but a sequence of characters: 7, E, 3, 0, space, 0, 0, 0, 0, space, 3, 0, 8, 1. Each character takes up two bytes. You can just use OutputStream's regular write methods:
or using the bulk write:
Note that you need a cast for 0x81 since its decimal value is 129, and that exceeds the maximum value for bytes. The cast turns it into a byte, but don't worry, the receiver will still get 0x81.

 
E. Domenech
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob, I changed the way I send the response to the device, added a break on the loop and I'll try to change the streams to regular InputStream and OuputStream.

Next I'll try to make a thread for each connection since many devices will send data to the server.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!