gpt4 book ai didi

Java Socket 等待 UTF8

转载 作者:行者123 更新时间:2023-12-01 11:36:45 24 4
gpt4 key购买 nike

我正在尝试自己实现一个客户端-服务器应用程序。到目前为止,它的工作原理是,当我通过另一个应用程序(例如网络浏览器)访问端口时,服务器应用程序被阻止。

是否有任何简单的方法/良好实践来检查连接应用程序是否是“客户端应用程序”?

这是一个监听端口 8080 的套接字的简短示例。套接字等待 2 个字符串。如果您现在连接浏览器 (localhost:8080),则连接已建立,但正在等待第一个 UTF8。

public class MainSocket {

public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(8080);
while (true) {
try {
Socket clientSocket = serverSocket.accept();
System.out.println("Connection established");
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
System.out.println(in.readUTF());
System.out.println(in.readUTF());
in.close();
clientSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

最佳答案

您正在调用DataInputStream.readUTF8。预计数据如下:

First, two bytes are read and used to construct an unsigned 16-bit integer in exactly the manner of the readUnsignedShort method . This integer value is called the UTF length and specifies the number of additional bytes to be read. These bytes are then converted to characters by considering them in groups. The length of each group is computed from the value of the first byte of the group. The byte following a group, if any, is the first byte of the next group.

(等)

换句话说,这不仅仅是 UTF-8。它是带有长度前缀的 UTF-8 的细微变化。这不是浏览器要写入连接的内容。基本上,DataInputDataOutput 是对称的,但并不完全通用 - 它们通常一起使用,一侧通过 DataInput 读取内容另一侧已用DataOutput写入。

如果你只想读取UTF-8的行,你可以使用:

try (Reader inputReader = new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(inputReader)) {
System.out.println(read.readLine());
System.out.println(read.readLine());
}

(现在还不清楚您是否应该期望浏览器将 UTF-8 写入套接字,但我想说的是,上面的内容更有可能让您进入下一步......)

关于Java Socket 等待 UTF8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29896806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com