//====================================================================== //接收数据 //====================================================================== protected void DoReceiveInThread() { //子线程 this.LogVerbose(); bool result = false; try { EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = m_socket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { if (!RemoteEndPoint.Equals(remotePoint)) { Debuger.LogVerbose("收到非目标服务器的数据!"); return; } m_bufferReceive.Attach(m_RecvBufferTemp, cnt); byte[] m_32b = new byte[4]; m_bufferReceive.ReadBytes(m_32b, 0, 4); uint sid = BitConverter.ToUInt32(m_32b, 0); if (sid == 0) { //Session过期了 HandleServerError((int)NetErrorCode.SessionExpire); return; } byte[] dst = new byte[cnt]; Buffer.BlockCopy(m_RecvBufferTemp, 0, dst, 0, cnt); m_RecvBufQueue.Push(dst); } } catch (Exception ex) { this.LogWarning("接收数据出错:{0}", ex.Message); onReceiveError.InvokeSafe(this, (int)NetErrorCode.UnkownError, ex.Message); } }
private void DoReceiveInThread() { EndPoint remotePoint = IPUtils.GetIPEndPointAny(AddressFamily.InterNetwork, 0); int cnt = m_socket.ReceiveFrom(m_RecvBufferTemp, m_RecvBufferTemp.Length, SocketFlags.None, ref remotePoint); if (cnt > 0) { m_bufferReceive.Attach(m_RecvBufferTemp, cnt); byte[] m_32b = new byte[4]; m_bufferReceive.ReadBytes(m_32b, 0, 4); uint sid = BitConverter.ToUInt32(m_32b, 0); lock (m_mapSession) { KcpSession session = null; if (sid == 0) { //来自Client的第1个包,只能是鉴权包 session = new KcpSession(NewSessionID(), m_listener); m_mapSession.Add(session.Id, session); } else { session = m_mapSession[sid]; } if (session != null) { session.Active(m_socket, remotePoint as IPEndPoint); session.DoReceiveInGateway(m_RecvBufferTemp, cnt); } else { this.LogWarning("无效的包! sid:{0}", sid); //需要返回给客户端,Session无效了,直接返回一个Sid为0的包 //当客户端收到包好,会抛出Session过期事件 //因为正常情况下,客户端收到的Session肯定不为0 m_socket.SendTo(new byte[4], remotePoint); } } } }