ObjectOutputStream.writeBytes(String s)意外的输出值

时间:2016-06-14 13:56:27

标签: java android objectoutputstream

我正在使用ObjectOutputStream对象操作系统将客户端Android应用程序中的String msg发送到c ++服务器。

我知道服务器必须如何接收我的消息: 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:我无法更改服务器代码。

1 个答案:

答案 0 :(得分:0)

使用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"文字输出)。

明确给出编码。

相关问题