android socket DataOutputStream.writeUTF [英] android socket DataOutputStream.writeUTF

查看:541
本文介绍了android socket DataOutputStream.writeUTF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写套接字客户端:

clientSocket = new Socket("192.168.1.102", 15780);
outToServer = new DataOutputStream(clientSocket.getOutputStream());

一切正常。但我不会发送到服务器 UTF -8格式的消息并执行此操作:

All works. But I wont to send to server UTF-8 format messages and do so:

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

消息变为:

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

Tell me please why? How correctly send UTF messages?

推荐答案

writeUTF()文档说:


首先,将两个字节写入输出流,就好像writeShort方法一样,给出了要遵循的字节数。该值是实际写出的字节数,而不是字符串的长度。

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,然后使用 写( )

You can encode the string as utf-8 yourself and then send the resulting byte array to the server using write():

byte[] buf = "hello".getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);

这篇关于android socket DataOutputStream.writeUTF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆