我們需要實現一個Socket客戶端,它應該連接到一個接受TCP連接的服務器。如果我通過netcap與服務器進行通信,我會立即得到它的響應(通過命令行)。Java通過Socket發送和接收多條消息
的工作流程是:
nc 99.0.99.84 20000
然後我發送連接請求到服務器
*99*0##
我得到的ACK響應返回
*#*1##
我送我的要求
*#18*802*86##
我得到的迴應回
*#18*802*86*222241400##*#*1##
一切都是通過命令行非常快。
所以我試圖用這種方式
try {
Socket socket = new Socket("99.0.99.84", 20000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Start");
Thread.sleep(1000);
String connectionRequest ="*99*0##";
System.out.println("Sending connection request " + connectionRequest);
out.println(connectionRequest);
String connResponse = in.readLine();
System.out.println("Response to connection is " + connResponse);
Thread.sleep(500);
String payload ="*#18*802*86##";
System.out.println("Sending " + payload);
out.println(payload);
String response = in.readLine();
System.out.println("Response is " + response);
out.close();
in.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
使用攝像機時,客戶端採用了大量的時間,然後與響應退出該連接響應= null與一個客戶端的Socket做到這一點
Sending connection request*99*0##
Response to connection is *#*1##*#*1##
Sending *#18*802*86##
Response is null
有什麼問題嗎?
響應以'\ r','\ n'還是'\ r \ n'結尾? readLine將讀取直到該點,然後等待它。 – icabod
沒有...沒有行尾元素... – besmart
感謝您的評論我解決了使用讀取()通過讀取char每個字符 – besmart