I'm changing a C++ client to a Java version - just an exercise I'm trying more than anything else.
The orginal C++ code works perfectly well. The Servce side sends a DWORD then the client looks for this then reads the 253 bytes of data. I've tried this in Java with out much success, the client is dropping lots of packets ~ 1 in 20 come through. Below are a couple of different code blocks I've tried. If anyone can tell me when I'm going wrong I'm most appreciate it.
Thanks
Mark
Attempt 1:
//Create socket connection
try
{
client = new Socket("localhost", 7651);
//in = client.getInputStream();
reader = new BufferedReader(new
InputStreamReader(client.getInputStream(), "ISO-8859-1"));
}
catch (UnknownHostException e)
{
System.out.println("Unknown host: localhost");
System.exit(1);
}
catch (IOException e)
{
System.out.println("No I/O");
System.exit(1);
}
//Receive data from ROS SerialtoNetwork server
while (true)
{
// Read repeatedly until the expected number of chars has been read:
char[] buf = new char[300];
int numberRead = 0;
int numberToRead = 257;
for (int totalCharsRead = 0; totalCharsRead < numberToRead; )
{
int numberLeft = numberToRead - totalCharsRead;
try {
numberRead = reader.read(buf, totalCharsRead, numberLeft);
if (numberRead < 0)
{
// premature end of data
break;
}
else
{
totalCharsRead += numberRead;
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String lstr = new String(buf);
System.out.print(lstr);
System.out.println("");
System.out.println("Bytes Received:" + numberRead);
}
Attempt 2:
//Create socket connection
try
{
client = new Socket("localhost", 7651);
in = client.getInputStream();
}
catch (UnknownHostException e)
{
System.out.println("Unknown host: localhost");
System.exit(1);
}
catch (IOException e)
{
System.out.println("No I/O");
System.exit(1);
}
//Receive data from ROS SerialtoNetwork server
try
{
while (true)
{
byte[] cbuf = new byte[300];
int lBytesAvail = in.available();//read(cbuf, 0, 4);
if (lBytesAvail > 253)
{
in.read(cbuf, 0, 4);
int lBytesRead = in.read(cbuf, 0, 253);
String lstr = new String(cbuf);
System.out.print(lstr);
System.out.println("");
System.out.println("Bytes Received:" + lBytesRead);
}
}
}
catch (IOException e)
{
System.out.println("Read failed");
System.exit(1);
}