Пример #1
0
 public void DelegateOnCloseEvent(int closeCode)
 {
     this.OnClose?.Invoke(WebSocketHelpers.ParseCloseCodeEnum(closeCode));
 }
Пример #2
0
        public async Task Receive()
        {
            WebSocketCloseCode closeCode = WebSocketCloseCode.Abnormal;

            await new WaitForBackgroundThread();

            ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[8192]);

            try
            {
                while (m_Socket.State == System.Net.WebSockets.WebSocketState.Open)
                {
                    if (m_CancellationToken.IsCancellationRequested)
                    {
                        break;
                    }
                    WebSocketReceiveResult result = null;
                    using (var ms = new MemoryStream())
                    {
                        do
                        {
                            result = await m_Socket.ReceiveAsync(buffer, m_CancellationToken);

                            ms.Write(buffer.Array, buffer.Offset, result.Count);
                        }while (!result.EndOfMessage);

                        ms.Seek(0, SeekOrigin.Begin);

                        if (result.MessageType == WebSocketMessageType.Text)
                        {
                            m_MessageListMutex.WaitOne();
                            m_MessageList.Add(ms.ToArray());
                            m_MessageListMutex.ReleaseMutex();
                        }
                        else if (result.MessageType == WebSocketMessageType.Binary)
                        {
                            m_MessageListMutex.WaitOne();
                            m_MessageList.Add(ms.ToArray());
                            m_MessageListMutex.ReleaseMutex();
                        }
                        else if (result.MessageType == WebSocketMessageType.Close)
                        {
                            await Close();

                            closeCode = WebSocketHelpers.ParseCloseCodeEnum((int)result.CloseStatus);
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("Exception while waiting for messages: " + e.Message);
                m_TokenSource.Cancel();
                m_TokenSource = null;
            }
            finally
            {
                await new WaitForUpdate();
                OnClose?.Invoke(closeCode);
            }
        }