java – android socket DataOutputStream.writeUTF

前端之家收集整理的这篇文章主要介绍了java – android socket DataOutputStream.writeUTF前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我写套接字客户端:
clientSocket = new Socket("192.168.1.102",15780);
outToServer = new DataOutputStream(clientSocket.getOutputStream());

一切都有效.但我不会发送到服务器UTF-8格式的消息,并这样做:

outToServer.writeBytes("msg#");//server tag
outToServer.writeUTF("hello");
//outToServer.writeUTF(str); //or another string
outToServer.writeBytes("\n");
outToServer.flush();

消息变成这样:

请告诉我为什么?如何正确发送UTF消息?

解决方法

writeUTF() documentation说:

First,two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out,not the length of the string.

您可以自己将字符串编码为utf-8,然后使用write()生成的字节数组发送到服务器:

byte[] buf = "hello".getBytes("UTF-8");
outToServer.write(buf,buf.length);
原文链接:https://www.f2er.com/android/128267.html

猜你在找的Android相关文章