java – android socket DataOutputStream.writeUTF

java – android socket DataOutputStream.writeUTF,第1张

概述我写套接字客户端: clientSocket = new Socket("192.168.1.102", 15780);outToServer = new DataOutputStream(clientSocket.getOutputStream()); 一切都有效.但我不会发送到服务器UTF-8格式的消息,并这样做: outToServer.writeBytes("msg#");//serve 我写套接字客户端:
clIEntSocket = new Socket("192.168.1.102",15780);outToServer = new DataOutputStream(clIEntSocket.getoutputStream());

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

outToServer.writeBytes("msg#");//server tagoutToServer.writeUTF("hello");//outToServer.writeUTF(str); //or another stringoutToServer.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);
总结

以上是内存溢出为你收集整理的java – android socket DataOutputStream.writeUTF全部内容,希望文章能够帮你解决java – android socket DataOutputStream.writeUTF所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1148223.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存