C++クライアントをJavaバージョンに変更しています。これは何よりも挑戦しています。Javaクライアントを使用してTCPを読み取るときにパケットが欠落/欠落する
元のC++コードは完全にうまく機能します。 Servce側がDWORDを送信すると、クライアントはこれを探して、次に253バイトのデータを読み取ります。私はJavaで多くの成功を収めてこれを試してきました。以下は私が試した異なるコードブロックのカップルです。誰かが私が間違っているとき私に言うことができるなら、私はそれを最も感謝しています。
おかげ
マーク
試み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: "試行1" では
//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バイトのうち1バイトしか読み込まれないということですか? 2つの問題は完全に分離されており、前者はおそらくハードウェアに関連している(または接続に関連している)おそらく後者はおそらくコード内のバグです。 – SRM