Ejemplo n.º 1
0
 /// <summary>
 /// 分发消息
 /// </summary>
 /// <param name="msgId"></param>
 public void DispatchMsg(int msgId, WebSocketMsgData data)
 {
     if (netActionCallBack.ContainsKey(msgId))
     {
         for (int i = 0; i < netActionCallBack[msgId].Count; i++)
         {
             netActionCallBack[msgId][i]?.Invoke(data);
         }
     }
     RemoveAllCallBack(msgId);
 }
Ejemplo n.º 2
0
    /// <summary>
    /// 异步接受消息
    /// </summary>
    /// <param name="client"></param>
    private async void StartReceiving()
    {
        while (true)
        {
            if (webSocket == null)
            {
                break;
            }
            var array  = new byte[4096];
            var result = await webSocket.ReceiveAsync(new ArraySegment <byte>(array), CancellationToken.None);

            if (result.MessageType == WebSocketMessageType.Binary)
            {
                int msgId = int.Parse(Encoding.Default.GetString(array, 0, 4));
                GameDebug.Log("收到消息id:" + msgId);
                byte[] tem = new byte[array.Length];
                Array.Copy(array, tem, array.Length);
                byte[] receive = new byte[result.Count - 4];
                Array.Copy(array, 4, receive, 0, result.Count - 4);
                WebSocketMsgData data = new WebSocketMsgData(msgId, receive);
                webSocketMsgCenter.DispatchMsg(data.msgId, data);
            }
        }
    }