美文网首页“云大物移智农”专题
unity 使用WebSocket开发聊天

unity 使用WebSocket开发聊天

作者: 安宇辛 | 来源:发表于2021-03-22 11:29 被阅读0次

    1.搭建WebSocket

    
            public async static void WebSocket()
            {
                try
                {
                    ws = new ClientWebSocket();
                    ct = new CancellationToken();
                    //添加header
                    //ws.Options.SetRequestHeader("X-Token", "eyJhbGciOiJIUzI1N");
                    //ws://192.168.1.249:12000?group_id=16&user_id=5
                    string kurl = string.Format("{0}?group_id={1}&user_id={2}&secret={3}", socketUrl, GameData.teamId, GameData.userId, Sha256(string.Format("{0}:{1}:{2}", GameData.userId, GameData.teamId, Signature)));
                    Uri url = new Uri(kurl);
                    await ws.ConnectAsync(url, ct);
                    heartbeat = true;
                    if (mTimer==null) {
                        mTimer = Schedule.ins.AddTimer(5.0f, -1, 0, false, heartTime);
                    }
                   
                    while (true)
                    {
                        var result = new byte[5000];
                        await ws.ReceiveAsync(new ArraySegment<byte>(result), new CancellationToken());//接受数据
                        var lastbyte = ByteCut(result, 0x00);//去除多余的数据
                        var str = Encoding.UTF8.GetString(lastbyte, 0, lastbyte.Length);
    
                        //LogUtils.Log(str);
                        if (str[0] == 'Q')
                        {
                            //LogUtils.Log("心跳包");
                            heartbeat = true;
                            if (!isws)
                            {
                                isws = true;
                            }
     
                        }
                        else
                        {
                            //同一时间有数据  就不会再发Q   有数据就表示没有掉线
                            heartbeat = true;
                            if (!isws)
                            {
                                if (GameData.teamId != 0)
                                {
                                    isws = true;
                                }
                                else
                                {
                                    //用户已经离开团队
                                    return;
                                }
                               
                            }
                            ////判断2个条件 检查是否没有接受完
                            string kst = str.Substring(str.Length - 17, 4);
                            if (str[str.Length - 1].ToString() != "}")
                            {
    
                                if (kst != "time")
                                {
                                    strData += str;
                                }
    
                            }
                            else
                            {
                                strData += str;
                                JsonError(str);//数据解析错误检查
    
                            }
                            //strData += str;
                            //errorMethod(str);
    
    
    
    
                        }
                        if (GameData.network == false) {
                            EventSystem.Instance.Emit<int>(TileClashGame.EventType.GameUnNetwork, 1);
                        }
    
                       
    
                    }
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex.Message);
                    if(ex.Message== "The remote party closed the WebSocket connection without completing the close handshake.")
                    {
                        //GamePopUpLabel.Show2("服务器关闭", false);
                        isws = false;
                        WsChange();
                    }
    
                    if(ex.Message == "Unable to connect to the remote server") {
                        //GamePopUpLabel.Show2("网络不稳定", false);
                        GameData.network = false;
                        EventSystem.Instance.Emit<int>(TileClashGame.EventType.GameUnNetwork, 0);
                        isws = false;
                        WsChange();
                    }
    
                }
            }
    

    2.去除多余字符

     public static byte[] ByteCut(byte[] b, byte cut)
            {
                var list = new List<byte>();
                list.AddRange(b);
                for (var i = list.Count - 1; i >= 0; i--)
                {
                    if (list[i] == cut)
                        list.RemoveAt(i);
                }
                var lastbyte = new byte[list.Count];
                for (var i = 0; i < list.Count; i++)
                {
                    lastbyte[i] = list[i];
                }
                return lastbyte;
            }
    

    3.心跳包

      private static void heartTime()
            {
                if (!isws)
                {
                    return;
                }
                if (heartbeat)
                {
                    heartbeat = false;
                    if (isws)
                    {
                        ws.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("P")), WebSocketMessageType.Binary, true, ct); //发送数据
                    }
                    
                }
                else
                {
                    LogUtils.Log("我掉线了,进行断线重连");
                    isws = false;
                    if (GameData.teamId != 0)
                    {
                        WsChange();
                    }
                   
                }
    
    
    
    
            }
    

    相关文章

      网友评论

        本文标题:unity 使用WebSocket开发聊天

        本文链接:https://www.haomeiwen.com/subject/iscvcltx.html