gpt4 book ai didi

Java Tcp 套接字发送额外的数据?

转载 作者:可可西里 更新时间:2023-11-01 02:39:03 25 4
gpt4 key购买 nike

我有一个将在 java 中发送数据的类,服务器需要特定的字符串才能实际工作。

我正在发送正确的字符串,这是连接和发送过程:

   // CONNECT
try {

// GET SERVER IP
InetAddress serverAddr = InetAddress.getByName(this.terminalIp);

// CREATE SOCKET
Socket hcmSocket = new Socket(serverAddr,this.terminalPort);

PrintWriter sendingStream = new PrintWriter(new BufferedWriter(new OutputStreamWriter(hcmSocket.getOutputStream())), true);
BufferedReader recivingStream = new BufferedReader(new InputStreamReader(hcmSocket.getInputStream()));

// SEND REQUEST
sendingStream.println("00 0012552 003365 004152");

服务器拒绝它,即使它是正确的。

当我跟踪与 wireshark 的连接时,我看到发送的十六进制添加了一个额外的 0x000a,这是一个 Line Feed

我的问题是我不想发送它,我要确保我发送的字符串末尾没有多余的空格来创建它。

这是我要发送的十六进制:30 30 1c 30 30 31 31 30 30 30 1c 30 30 33 32 35 32 1c 30 30 34 31 32 35 31

但实际发送的是:30 30 1c 30 30 31 31 30 30 30 1c 30 30 33 32 35 32 1c 30 30 34 31 32 35 31 0a

会不会是 sendingStream 自动加入的?

最佳答案

My problem is that I don't want that to be sent, I am making sure that the string I am sending it has no extra white space at the end to create this.

不,你不是。

看看你的代码:

sendingStream.println("00 0012552 003365 004152");

来自 PrintWriter.println(String) 的文档:

Prints a String and then terminates the line. This method behaves as though it invokes print(String) and then println().

这就是为什么您要使用行终止符的原因 - 您需要它

如果你不想要它,只需调用 print 而不是 println。理想情况下,完全摆脱 PrintWriter,因为它会向您隐藏异常。只需使用 BufferedWriter 即可。 (我个人会明确指定字符集,尽管我知道在 Android 上期望默认为 UTF-8 是合理的...)

关于Java Tcp 套接字发送额外的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860308/

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