我正在将 C++ 客户端更改为 Java 版本——这只是我尝试的一个练习。
原始的 C++ 代码运行良好。Servce 端发送一个 DWORD,然后客户端查找它,然后读取 253 字节的数据。我已经在 Java 中尝试过,但没有取得很大成功,客户端丢弃了大量数据包〜 20 分之 1 的数据包通过。下面是我尝试过的几个不同的代码块。如果有人能告诉我什么时候出错,我将不胜感激。
谢谢
标记
尝试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);
}
尝试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);
}