[英]Sending String from Java client to NodeJS server via socket also sends unwanted characters
我想使用套接字將一個字符串數組從我的 Java 客戶端發送到我的 NodeJS 服務器。 我的意圖更復雜,但我認為一切都可以簡化為下一行代碼:
爪哇
Socket s = new Socket("localhost", 6666);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("test"); // also tried writeChars and writeBytes
節點
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString())
});
}).listen(6666);
簡單地運行服務器,然后是客戶端,我得到:
我知道我發送數據的方式有問題。 也許它需要某種序列化,但我找不到一些明確的步驟來做到這一點。 謝謝你。
使用 OutputStreamWriter 而不是 DataOutputStream:
Socket s = new Socket("localhost", 6666);
OutputStreamWriter out = new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8);
out.write("test");
out.flush();
DataOutputStream
旨在與DataInputStream
Java 類一起使用,它們使用的數據交換格式有些不標准。 這尤其適用於writeUTF
方法:它首先將字符串的長度寫入 2 字節二進制數。 然后它使用非標准字符編碼寫入字符串的字符。
如果您正在與不是用 Java 編寫的軟件交換信息,那么不使用 DataOutput/InputStream 類會更容易。
根據我的經驗,通過 Socket 發送字符串的最安全方法是發送它的字節數組,如下所示:
public static void main(String[] args) {
try (Socket s = new Socket("localhost", 6666)) {
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("test utf");
dout.writeUTF("hello from ☕");
dout.writeUTF("\n");
dout.write("test byte[]".getBytes());
dout.write("hello from ☕".getBytes());
dout.write("I support unicode ✁ ✂ ✃ ✄ ✆".getBytes());
} catch (IOException ioe) {
// do nothing
}
}
但即使通過復制您的代碼,我也無法重現未知字符:
~/Projects/scratch via ⬢ v12.18.3
➜ node server.js
connected
test utfhello from ☕
test byte[]hello from ☕I support unicode ✁ ✂ ✃ ✄ ✆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.