この問題があります。 ローカルネットワークに接続されたスケールから重量を読み取る必要があります。 ハイパーターミナルから私はポート、オープン接続でipに接続し、文字列 "XN"を送り、入力し、スケールはハイパーターミナルに文字列としての新しい行を書き出します。 私はsocketを使って同じことをしようとしましたが、何らかの結果を得ることができます。 私を助けるいくつかの例に私に対処できますか?これは私が成功せずに試みたコードです。Javaのソケットから返信を受け取ることができません
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
echoSocket = new Socket(IpBilancia, Porta);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: " + IpBilancia);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to" + IpBilancia);
}
try
{
os.writeBytes("XN");
os.writeByte('\n');
os.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String Peso;
while ((Peso = input.readLine()) != null)
{
System.out.println("echo: " + is.readLine());
}
os.close();
is.close();
echoSocket.close();
} catch (IOException e) {
System.err.println("I/O failed on the connection to" + IpBilancia);
}
EDIT1:whileループで立ち往生
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try
{
echoSocket = new Socket(IpBilancia, Porta);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: " + IpBilancia);
}
catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to" + IpBilancia);
}
try
{
os.writeBytes("XN");
os.writeByte('\n');
os.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String Peso;
while ((Peso = input.readLine()) != null)
{
System.out.println("echo: " + is.readLine());
}
os.close();
is.close();
echoSocket.close();
} catch (IOException e) {
System.err.println("I/O failed on the connection to" + IpBilancia);
}
デバッグ滞在。ループに入ることはありません。 ここで停止します while((Peso = input.readLine())!= null) 何もしません。
'while'ループの中で' is.readLine() 'を実行しているので、**の行**を2回読み込みますが、' os'には1行しか書き込まれません。あなたは 'System.out.println(" echo: "+ Peso);'を意味しましたか? – Jesper
はい。しかし問題は、input.readLine()が空であることです。私はなぜこれを理解していない。ハイパーターミナルから実行すると結果が得られます。ありがとうあなたの助けを – mmauro
@ Jesperのコメントを無視したので、私はそれを繰り返します。ループ内で 'is.readLine()'を2回呼び出し、**最初のis.readLine()**の結果を破棄します。 –