我正在將C++客戶端更改爲Java版本 - 僅僅是一個練習,我正在嘗試比其他更多的任務。使用Java客戶端讀取TCP時丟失/丟失數據包
原始C++代碼完美地工作。 Servce端發送一個DWORD,然後客戶端查找它,然後讀取253個字節的數據。我已經在Java中嘗試了這個,取得了很大的成功,客戶端丟棄了大量的數據包,大約有20個數據包通過。下面是我嘗試過的幾個不同的代碼塊。如果有人能告訴我什麼時候出錯,我會非常感激。
感謝
馬克
嘗試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);
}
你是什麼意思**客戶端丟失大量的數據包**?您是否在監視網絡流量,並看到實際的數據包被丟棄?或者你的意思是隻讀了20個字節中的一個?這兩個問題是完全分開的,前者可能與硬件有關(或與連接有關),後者可能是代碼中的一個錯誤。 – SRM