[英]BufferedReader in Socket Programming
當我嘗試從客戶端發送輸入時,如果我不在字符串末尾連接“\r\n”,我的輸入流將永遠等待。 我看過各種類似的帖子,但找不到合適的解決方案。 我的代碼如下:
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
if (in.ready()) {
if ((line = in.readLine()) != null) {
System.out.println("Received from client: " + line);
out.write("Echoing: " + line);
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
try {
in.close();
clientSocket.close();
System.out.println("Closing connection from " + socketAddress + ", #" + connectionId);
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果您只想讀取已發送的部分數據,請使用read(char[])
方法而不是readLine
方法。 此方法以int
形式返回讀取的字符數。 例子:
char[] buffer = new char[2000];
int read;
if ((read = in.read(buffer)) != -1) {
String line = new String(buffer, 0, read);
System.out.println("Received from client: " + line);
out.write("Echoing: " + line);
out.flush();
}
接下來您會看到此代碼有時無法讀取您從 PHP 發送的整個消息,或者將兩條或多條消息作為一條讀取。
如果你想解決這個問題:
這永遠不會奏效,也不是因為 PHP 或 Java。 您正在使用 TCP,一個面向 stream 的協議。 無法保證您從 PHP 程序寫入到套接字的消息將一體地到達接收器。 該消息可能被分解,您需要多個套接字 function 調用來讀取它。 或者它可能 go 另一個方向,並且單個調用read
返回多個消息。
解決方案是為消息添加某種框架,以便接收者知道何時收到完整的消息。 如果消息本身是單行,則始終以換行符結束消息作為框架。 另一種解決方案是放棄 TCP 並改用面向消息的協議(如 UDP),但這會帶來其自身的復雜性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.