[英]Writing bytes to java socket
我正在嘗試在創建的Java套接字中寫入0x87。
tcpSocket = new Socket(server, port);
tcpWriteToServer = new PrintWriter(tcpSocket.getOutputStream(), true);
byte [] header = {0x8, 0x7};
tcpWriteToServer.print(header);
在服務器端,我得到:
Incoming Bytes: 0x5b 0x42 0x40 0x34 0x32 0x65 0x62 0x35 0x62 0x38 0x38
我試圖解決問題,只發送一個字節:
tcpWriteToServer.print(header[0]);
為此,我最終得到:
Incoming Bytes: 0x38
我不確定如何讀取“ 0x38”中的“ 3”。 當我嘗試發送“ 0x7”時,我讀到“ 0x37”。
服務器端是用python編寫的,我在使用python發送字節並正確讀取時沒有任何問題。
知道我可能會缺少什么嗎?
知道我可能會缺少什么嗎?
您必須決定要編寫文本還是二進制文件。 合並它們可能是使自己困惑的好方法。
我建議您在這種情況下使用二進制文件。
tcpSocket = new Socket(server, port);
out = tcpSocket.getOutputStream();
out.write(0x8);
out.write(0x7);
您也可以像這樣緩沖輸出。
out = new BufferedOutputStream(tcpSocket.getOutputStream());
out.write(0x8);
out.write(0x7);
out.flush();
如果您有字節數組,則可以一次性寫入。
byte[] header = { .... };
out.write(header);
我不確定如何讀取“ 0x38”中的“ 3”。 當我嘗試發送“ 0x7”時,我讀到“ 0x37”。
沒有print(byte)
但是有一個print(int)
所以當您這樣做時
print(8);
它與
print(Integer.toString(8));
要么
print("8");
要么
print('8')
並且ASCII中的'8'= 0x38
傳入字節:0x5b 0x42 0x40 0x34 0x32 0x65 0x62 0x35 0x62 0x38 0x38
如果您打印出每個字節的字符表示形式
byte[] bytes = {0x5b, 0x42, 0x40, 0x34, 0x32, 0x65, 0x62, 0x35, 0x62, 0x38, 0x38};
for (byte b : bytes){
System.out.print((char)b);
}
您會看到您的代碼發送了[B@42eb5b88
。
發生這種情況是因為因為PrintWriter沒有print(byte[])
方法,所以它使用了print(Object obj)
,該方法只發送對象obj
String表示形式。 此類字符串是使用String.valueOf(obj)
創建的,該字符串內部使用obj.toString()
方法,該方法對於數組返回typeName
( [b
一維[
字節數組b
), @
和hexHashCode
。
換句話說,您不是發送header
數組的內容,而是發送其toString()
方法的結果。
如果要發送字節,則使用Stream
(用於處理文本而不是字節的Writers固件)及其write(byte[])
方法更容易。 如果您還希望發送文本而不是字節,則可以使用PrintStream
PrintStream tcpWriteToServer = new PrintStream(tcpSocket.getOutputStream(), true);
tcpWriteToServer.write(header);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.