简体   繁体   English

android socket DataOutputStream.writeUTF

[英]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.

相关问题 为什么 DataOutputStream.writeUTF() 在开头添加额外的 2 个字节? - Why does DataOutputStream.writeUTF() add additional 2 bytes at the beginning? 通过DataOutputStream.writeUTF()发送信息时出现奇怪的字符 - strange characters when sending information via DataOutputStream.writeUTF() 从DataOutputStream.writeUTF()读取时如何获取Java字符串的“原始”字节? - How to get 'original' bytes of a Java String when read from DataOutputStream.writeUTF()? 在线程中循环 DataOutputStream writeUTF - Looping DataOutputStream writeUTF in thread java.io.DataOutputStream 中的 writeUTF - writeUTF in java.io.DataOutputStream java socket writeUTF()和readUTF() - java socket writeUTF() and readUTF() 从DataOutputStream重新分配给BufferedOutputStream和FileOutputStream之后,再也无法使用writeUTF() - Not able to use writeUTF() anymore after reassigning to BufferedOutputStream and FileOutputStream from DataOutputStream 将套接字的OutputStream与DataOutputStream进行比较 - Compare the OutputStream of a Socket with a DataOutputStream 套接字 ObjectOutputStream writeUTF() 和 ObjectInputStream readUTF() 不起作用 - Socket ObjectOutputStream writeUTF() and ObjectInputStream readUTF() not working 在没有DataOutputStream和Socket的情况下关闭CipherOutputStream - Close CipherOutputStream without DataOutputStream & Socket
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM