private void Connection_Clarify(Connection aConnection, string aInfo, int aLevel) { ClarifyInfo(aInfo, aLevel); }
private void Clarify_Received(Connection aConnection, byte[] aBytes) { Received?.Invoke(aConnection, aBytes); }
/// <summary> /// 监听线程,接受客户端的连接请求 /// </summary> private void ListenThread() { if (m_TcpListener == null) { return; } // 启动监听 try { ClarifyInfo(string.Format("启动监听端口[{0}]……", ListenPort), 1); IsListening = true; m_TcpListener.Start(); } catch (System.Exception ex) { ClarifyInfo(string.Format("启动监听端口[{0}]发生错误:{1}", ListenPort, ex.Message), 0); IsListening = false; return; } // 主工作循环,等待并处理连接请求 ClarifyInfo(string.Format("开始监听端口[{0}]的主工作过程,等待连接请求……", ListenPort), 1); while (IsListening) { try { if (m_TcpListener.Pending()) { ClarifyInfo(string.Format("监听端口[{0}]收到连接请求……", ListenPort), 1); // 创建Connection对象,并建立连接 // 在连接建立之前,没有发现方法来识别请求者,这意味着在连接之前不可能区分请求者,因而也不可能根据不同的请求者建立不同性质的连接。 // 将连接能否建立以及如何建立交托给Connection类处理。 Connection aConnection = new Connection(m_ProtocolFactory == null ? null : m_ProtocolFactory.CreateProtocol()); aConnection.Clarify += new Connection.ClarifyDelegate(Connection_Clarify); aConnection.Received += new Connection.ReceivedDelegate(Clarify_Received); aConnection.BytesFrameReceived += new System.Action <Connection, byte[]>(Connection_BytesFrameReceived); aConnection.TextFrameReceived += new System.Action <Connection, string>(Connection_TextFrameReceived); aConnection.ObjectFrameReceived += new System.Action <Connection, object>(Connection_ObjectFrameReceived); aConnection.Disconnected += new System.EventHandler(Connection_Disconnected); System.Net.Sockets.TcpClient aTcpClient = m_TcpListener.AcceptTcpClient(); try { aConnection.WorkWith(aTcpClient); // 如果连接被接纳,则添加到连接表中,并发出通知。 m_Connections.Add(aConnection); ClarifyConnected(aConnection); } catch (System.Exception ex) { ClarifyInfo(string.Format("接受端口[{0}]上的连接请求发生错误:{1}", ListenPort, ex.Message), 0); // 如果连接被拒绝,则断开连接客户端。 aTcpClient.Close(); aConnection.Dispose(); } } else { // 如果没有连接请求,则进入短暂的休眠状态,以减少对系统响应的影响。 System.Threading.Thread.Sleep(IdleInterval); } } catch (System.Exception ex) { ClarifyInfo(string.Format("监听端口[{0}]的主工作过程循环发生错误:{1}", ListenPort, ex.Message), 0); } } }