[英]android socket DataOutputStream.writeUTF
I write socket client: 我写套接字客户端:
clientSocket = new Socket("192.168.1.102", 15780);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
All works. 一切都有效。 But I wont to send to server UTF -8 format messages and do so:
但我不会发送到服务器UTF -8格式的消息,并这样做:
outToServer.writeBytes("msg#");//server tag
outToServer.writeUTF("hello");
//outToServer.writeUTF(str); //or another string
outToServer.writeBytes("\n");
outToServer.flush();
Messages become such: 消息变成这样:
Tell me please why? 请告诉我为什么? How correctly send UTF messages?
如何正确发送UTF消息?
writeUTF()
documentation says: writeUTF()
文档说:
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow.
首先,将两个字节写入输出流,就好像通过writeShort方法一样,给出了要遵循的字节数。 This value is the number of bytes actually written out, not the length of the string.
该值是实际写出的字节数,而不是字符串的长度。
You can encode the string as utf-8 yourself and then send the resulting byte array to the server using write()
: 您可以自己将字符串编码为utf-8,然后使用
write()
将生成的字节数组发送到服务器:
byte[] buf = "hello".getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.