Unity - A计划(永久有效期) 扫二维码继续学习 二维码时效为半小时

(207评价)
优惠后 ¥1899.00优惠前 ¥2499.00 双十一全年最大力度限时优惠
1对1 答疑即时回复7天无理由退款30天价保提问必答

服务保障

1对1 答疑

提供专属的一对一在线答疑,快速答疑解惑。

即时回复

及时响应学习咨询,帮助解决问题。

7天无理由退款

购买后7天内可申请无理由退款。

30天价保

购买后30天内如遇降价,可申请价保。

提问必答

对于提问做到有问必答,帮您扫清学习过程中的种种障碍

在Unity中如何用c#将汉字转换成字节流发送到服务器端,然后进行解码?
赵宇发起了话题2017-11-27
1
回复
1907
浏览

//添加字符串
    public void AddString(string str)
    {

        Int32 len = str.Length;
        byte[] lenBytes = BitConverter.GetBytes (len);
        //byte[] strBytes = System.Text.Encoding.UTF8.GetBytes (str);
        Encoding gb2312= System.Text.Encoding.GetEncoding(936);
        byte[] strBytes = gb2312.GetBytes(str);
        if(bytes == null)
            bytes = lenBytes.Concat(strBytes).ToArray();
        else
            bytes = bytes.Concat(lenBytes).Concat(strBytes).ToArray();
    }
    
    //从字节数组的start处开始读取字符串
    public string GetString(int start, ref int end)
    {
        if (bytes == null)
            return "";
        if (bytes.Length < start + sizeof(Int32))
            return "";
        Int32 strLen = BitConverter.ToInt32 (bytes, start);
        if (bytes.Length < start + sizeof(Int32) + strLen)
            return "";

        string str = System.Text.Encoding.UTF8.GetString(bytes,start + sizeof(Int32),strLen);
        end = start + sizeof(Int32) + strLen;
        return str;
    }

我用的是Socket服务器,当客户端发送汉字类型的字符串的时候服务器端就会报错,字母和数字就没问题

 

所有回复
  • siki • 2017-11-29

    客户端使用的utf8的编码格式,服务器端也要使用utf8的编码格式,你服务器端使用的gb2312,编码格式不一样导致的

    还有-5条回复,点击查看
    你还没有登录,请先登录或注册!
发表回复
你还没有登录,请先 登录或 注册!