[英]Java socket client doesn't stop reading the data
您好,我正在嘗試在 Java 中執行套接字客戶端,但客戶端仍在讀取數據並且不繼續執行程序。 有任何想法嗎?
這是代碼:
import java.io.*;
import java.net.Socket;
public class SocketTeste {
public static void main(String[] args) {
try {
Socket client = new Socket("127.0.0.1", 1987);
System.out.println("Got connection");
DataInputStream handshake = new DataInputStream(client.getInputStream());
String handshakePure = handshake.readUTF();
System.out.println("Got the handshake");
System.out.println(handshakePure);
DataOutputStream saida = new DataOutputStream(client.getOutputStream());
saida.writeUTF("Got it!");
saida.flush();
saida.close();
String returnedData = handshake.readUTF();
System.out.println(returnedData);
handshake.close();
client.close();
} catch (Exception e) {
System.out.println("ERROR: " + e);
}
}
}
我認為這無關緊要,但套接字服務器是 PHP 套接字服務器。
DataInputStream.readUTF
需要一種獨特的奇怪消息格式。 它讀取的前兩個字節被解釋為要讀取的字符串的長度,采用大端二進制格式。 然后是一個奇怪的非標准文本編碼,類似於但不兼容 UTF-8。 很可能您不應該使用DataInputStream.readUTF
來讀取程序中的數據,除非您首先使用其對應的DataOutputStream.writeUTF
來寫入它。
根據您的評論,聽起來您的通信協議是基於文本行的。 要讀取文本行,您可以使用例如BufferedReader
class。
BufferedReader handshake = new BufferedReader(new InputStreamReader(client.getInputStream(), StandardCharsets.UTF_8));
String handshakePure = handshake.readLine();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.