// 监听客户端请求 void Listen() { try { IPEndPoint iPEndPoint = new IPEndPoint(m_ipAddress, m_ipPort); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.Bind(iPEndPoint); m_socket.Listen(400); CommonUtil.Log("ipPort:" + m_ipPort); CommonUtil.Log("服务器启动成功..."); // 心跳检测 //ClientInfoManager.startCheckHeartBeat(); while (m_isStart) { Socket socketToClient = m_socket.Accept(); Task t = new Task(() => { OnAccept(ClientInfoManager.addClientInfo(socketToClient)); }); t.Start(); } } catch (Exception ex) { CommonUtil.Log("SocketServer监听异常:" + ex); } }
public void DisconnectWithClient(ClientInfo client, bool isCloseConnect = false) { CommonUtil.Log("客户端断开:" + client.m_id); ClientInfoManager.deleteClientInfo(client); if (isCloseConnect) { client.m_socketToClient.Close(); } if (m_onSocketEvent_Disconnect != null) { m_onSocketEvent_Disconnect(client); } }
void OnReceive(object clientInfo) { try { ClientInfo client = (ClientInfo)clientInfo; Socket socketToClient = client.m_socketToClient; while (true) { byte[] rece = new byte[byteLength]; int recelong = socketToClient.Receive(rece, rece.Length, 0); if (recelong != 0) { string reces = Encoding.UTF8.GetString(rece, 0, recelong); //CommonUtil.Log(string.Format("收到客户端{0}原生数据{1} size={2}", client.m_id, reces, reces.Length)); // 过滤http非法请求 if (reces.StartsWith("GET") || reces.StartsWith("POST")) { CommonUtil.Log("收到客户端GET/POST非法请求,主动断开链接:" + client.m_id); DisconnectWithClient(client, true); break; } else { reces = client.m_endStr + reces; List <string> list = new List <string>(); bool b = CommonUtil.splitStrIsPerfect(reces, list, m_packEndFlag); if (b) { for (int i = 0; i < list.Count; i++) { if (list[i].CompareTo(m_heartBeatFlag) == 0) { ClientInfoManager.heartBeat(client); } else { if (m_onSocketEvent_Receive != null) { m_onSocketEvent_Receive(client, list[i]); } } } client.m_endStr = ""; } else { for (int i = 0; i < list.Count - 1; i++) { if (list[i].CompareTo(m_heartBeatFlag) == 0) { ClientInfoManager.heartBeat(client); } else { if (m_onSocketEvent_Receive != null) { m_onSocketEvent_Receive(client, list[i]); } } } client.m_endStr = list[list.Count - 1]; } } } // 与客户端断开连接 else { CommonUtil.Log("与客户端断开连接,id=" + client.m_id); DisconnectWithClient(client); return; } } } catch (Exception ex) { CommonUtil.Log("OnReceive异常:" + ex); } }