![](/img/trans.png)
[英]ObjectOutputStream methods: writeBytes(String str) vs writeUTF(String s);
[英]ObjectOutputStream.writeBytes(String s) unexpected output values
我正在使用ObjectOutputStream
對象os從客戶端Android應用程序向c ++服務器發送String msg。
我知道服務器必須如何接收我的msg:msg的每個char都存儲在一個字節數組中(received_msg [])。 我也知道服務器期望的確切消息(通過另一個c ++應用程序)。
我發送的數據是由1個字節數組和2個其他字符串組成的字符串。
我的問題:我已經使用PrintWriter
送我的數據,但我的服務器總是會顯示一些奇怪的字符received_msg
,在指數24〜28,我嘗試了很多的轉換來解決它,而放棄了這一點。 所以我嘗試用ObjectOutputStream
發送消息。 在客戶端使用ObjectOutputStream.writeBytes()
,服務器顯示幾乎正確的接收消息。 幾乎因為在開頭添加了字符。
這樣的事情:在服務器receive_msg:
index 0: ┐
index 1: i
index 2: ''
index 3: |
index 4: I //beginning of the message I actually wanted to send
index 5: S //every char following index 4 is good.
雖然我期待並且在“我”之前沒有發送任何東西。 我發送的消息開始如下:ISOXXXXX
所以我想知道是否有任何方法可以檢索ObjectOutputStream.writeBytes的REAL輸出。 我知道它是輸出,而不是輸入,仍然可以幫助我理解它是如何添加奇怪的標題。
提前感謝您的建議
我的發送功能
private void send(String o) {
System.out.println("socket");
try {
this.socket = new Socket(serverIP, portNumber);
os = new ObjectOutputStream(socket.getOutputStream());
//OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream());
//InputStreamReader in = new InputStreamReader(socket.getInputStream());
// PrintWriter pw = new PrintWriter(out, true);
System.out.println("Connected to server : " + this.socket.getInetAddress() + " on port " + this.socket.getPort());
System.out.println("from local address: " + this.socket.getLocalAddress() + " and port: " + this.socket.getLocalPort());
System.out.println("02. -> Sending an object...");
ArrayList<String> tempoStr = StringToByteArray(o);
String msg="";
for(String inStr :tempoStr)
msg+=inStr;
System.out.println("the message I ACTUALLY send is\n"+msg); //the result in console is EXACTLY the message I expect.
os.writeBytes(msg); //then when I check on the server: unexpected additionnal chars at the beginning.
os.flush();
// pw.write(msg);
//pw.flush();
System.out.println("send success");
} catch (IOException e) {
e.printStackTrace();
System.out.println("XX. Exception Occurred on Sending:" + e.toString() +"\n"+ e.getCause());
System.out.println("Socket creation failure or error on sending.");
}
}
PS:我無法更改服務器代碼。
不要使用ObjectOutputStream的(僅JAVA)。 有人可能會使用DataOutputStream,但在這里你似乎想要一些簡單的東西。
byte[] a = ...
String b = ...
OutputStream out = ...
out.write(a);
out.write((b + '\u0000').getBytes("UTF-8")); // Or "Windows-1252" / "ISO-8859-1"
out.flush();
我添加了'\\0'
因為它在C / C ++中用於終止字符串( 二進制輸出 )。 或者可能需要"\\r\\n"
( 文本輸出 )。
編碼是明確給出的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.