Android Linux Socket 数据传输错误

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenxiaoping1993/article/details/84138340

问题描述:
Android 端作为 Socket 服务端,Linux 端作为 Client 端,Android 端给 Linux 端

Android 侧发送数据代码:

public void sendMessage(final String msg){
        Log.d(TAG, "即将发送的数据  "+msg);
        // 发送的数据为  {"info":"The gps switch is not on","status":"Failed"} 
        new Thread(new Runnable() {
            @Override
            public void run() {
                if(outputStream!=null){
                    try {
                        writer= new DataOutputStream(outputStream);
                        writer.writeUTF(msg);  // 写一个UTF-8的信息
                        writer.flush();
                        //outputStream.write(msg.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                        // 发送消息失败
                    }
                }
            }
        }).start();
    }

发送的数据为 :
{“info”:“The gps switch is not on”,“status”:“Failed”}
但是对方收到的数据为:
7{“info”:“The gps switch is not on”,“status”:“Failed”}
首部都会莫名奇妙的出现一个数字或者冒号;

出现原因:
编码问题,我Android 端发送编码为 UTF-8
writer.writeUTF(msg); // 写一个UTF-8的信息
所以换成其它方式发送
writer.writeBytes(msg);
问题解决,特此记录;

猜你喜欢

转载自blog.csdn.net/chenxiaoping1993/article/details/84138340