// 开始接收消息 internal void StartReceiveMessage() { if (ConnectedCAS == 1 && !InnerSocket.Connected) { Disconnect(); } if (ConnectedCAS == 0 || DisposedCAS == 1 || InnerSocket.Available == 0) { return; } // 解析消息 try { while (InnerSocket.Available > 0) { ParseMessage(); } } catch { Disconnect(); } // 调用侦听 while (ReceiveMessageQueue.Count > 0) { SocketMessage message = ReceiveMessageQueue[0]; ReceiveMessageQueue.RemoveAt(0); if (MessageListeners[message.Info.Protocol] != null) { int length = MessageListeners[message.Info.Protocol].Count; for (int i = 0; i < length; i++) { if (i == 0) { InvokeListener(MessageListeners[message.Info.Protocol][i], message); } else { SocketMessage clone = message.Clone(); InvokeListener(MessageListeners[message.Info.Protocol][i], clone); clone.Dispose(); } } } message.Dispose(); } }
private void AsyncReadDone(IAsyncResult ar) { lock (_socketLocker) { try { var buff = (byte[])ar.AsyncState; if (buff == null) { return; } if (Sock.Client == null) { return; } int rin = Sock.Client.EndReceive(ar); if (rin > 0) { if (rin != 256) { Array.Resize(ref buff, rin); } _builder.AddBytes(buff); } else { LazyAsync.Invoke(Stop); } } catch (SocketException se) { #region "SocketErrors" switch (se.SocketErrorCode) { case SocketError.ConnectionAborted: { LazyAsync.Invoke(Stop); break; } case SocketError.ConnectionReset: { LazyAsync.Invoke(Stop); break; } case SocketError.Disconnecting: { LazyAsync.Invoke(Stop); break; } case SocketError.NetworkDown: { LazyAsync.Invoke(Stop); break; } case SocketError.NetworkReset: { LazyAsync.Invoke(Stop); break; } case SocketError.NoRecovery: { LazyAsync.Invoke(Stop); break; } case SocketError.NotConnected: { LazyAsync.Invoke(Stop); break; } case SocketError.OperationAborted: { LazyAsync.Invoke(Stop); break; } case SocketError.Shutdown: { LazyAsync.Invoke(Stop); break; } case SocketError.SocketError: { LazyAsync.Invoke(Stop); break; } case SocketError.TimedOut: { break; } default: { Trace.WriteLine("ss2:" + se.Message); Trace.WriteLine(se.StackTrace); break; } } #endregion } catch (ObjectDisposedException oe) { Trace.WriteLine("ss5:" + oe.Message); Trace.WriteLine(oe.StackTrace); } catch (NullReferenceException ne) { Trace.WriteLine("ss3:" + ne.Message); Trace.WriteLine(ne.StackTrace); } catch (Exception e) { Trace.WriteLine("ss4:" + e.Message); Trace.WriteLine(e.StackTrace); } while (_builder.SmQueue.Count > 0) { SocketMessage sm = _builder.SmQueue.Dequeue(); if (sm == null) { continue; } if (OnMessageReceived != null) { OnMessageReceived.BeginInvoke(this, (SocketMessage)sm.Clone(), null, null); } } LazyAsync.Invoke(AsyncRead); } }