![](/img/trans.png)
[英]How to read to inputstream in tcp socket communication for multiple formats in java
[英]Java communication with TCP socket and PIC stuck in read()
我嘗試通過Java應用程序與wifi(Flyport)中的µController通信。
我的Java應用程序有一個問題:它首先創建一個套接字以與Flyport服務器通信,然后發送消息並接收Flyport答案。
一切正常,直到讀取部分為止。 我正在輪詢BufferedReader的read()函數,直到它返回-1,但沒有。 第一次讀取可以正常工作,所有答案均為紅色,但是當應用程序嘗試再次讀取時,該應用程序仍處於阻塞狀態。
我的代碼很簡單:Java應用程序:
try (
Socket clientSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
)
{
...//Connection and sending message works fine
}
char[] buffer = new char[500];
while ((in.read(buffer)) != -1) { // first read() works fine, second read() stay stuck...
System.out.println(buffer); // display all answer sent by flyport
}
flyport中的代碼:
while(isClientConnected){
//check if client is still connected
...
//read client message
while((RxLen=TCPRxLen(sock))>0)
{
TCPRead(sock,bff,RxLen);
strcat(msg,bff);
}
//write back to the client that the order is received
TCPWrite(sock, msg, strlen(msg));
//process the client order
...
//Write to the client that the process is done
TCPWrite(sock, msg2, strlen(msg2));
}
Java應用程序使用第一個read()讀取msg和msg2。 msg和msg2的末尾帶有“ \\ r \\ n”。
有人能告訴我我錯了嗎? BufferedReading是否有一個函數可以告訴您剩下多少數據要讀取?
謝謝並恭祝安康。
注意:我嘗試在Java應用程序中使用一個小緩沖區,問題是一樣的,當沒有剩余要讀取的內容時,read()卡住了。
您正在從套接字讀取數據,直到流結束,而且也從未導致流結束,因為您從未關閉發送方的套接字。 關閉套接字,或者直到流結束才讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.