/// <summary> /// 等待客户端发送过来的数据 /// </summary> internal void WaitForData(AsynSocketArg state) { try { if (state != null && state.WorkSocket.Connected) { state.InitializeState(); state.WorkSocket.BeginReceive(state.GetBuffer(), 0, state.AutoBufferSize, 0, ReceiveCallback, state); } } catch (SocketException e) { OnSocketException(e.SocketErrorCode); } }
private void OnConnect(object sender, SocketAsyncEventArgs e) { if (e != null && e.SocketError == SocketError.Success) { //启动发送数据线程 SendDataService = new SendDataService(this); //启动异步接收数据操作 var state = new AsynSocketArg(); state.InitializeState(Socket, base.heardLength, false); WaitForData(state); } //处理其他操作 OnConnectEvent(e); }
/// <summary> /// 接受客户端连接 /// </summary> private void OnClientConnect(IAsyncResult asyn) { try { if (SocketConfig.Limit != 0 && SocketConfig.ClientList.Count > SocketConfig.Limit - 1) { OnSystemEvent(ServiceType.Limit, string.Format("超出连接限制:{0},拒绝连接。", SocketConfig.Limit)); return; } if (SocketConfig.ClientList.ToList().FindAll(c => c.ConnectTime > DateTime.Now.AddMinutes(-10)).Count > SocketConfig.Current - 1) { OnSystemEvent(ServiceType.Current, string.Format("限定时间内连接数超出限制:{0},拒绝连接。", SocketConfig.Current)); return; } var socket = socketListener.EndAccept(asyn); var client = new SocketPackage(socket, heardLength); OnClientConnect(client); SocketConfig.ClientList.Add(client); client.ClientEvent += Client_ClientEvent; client.ConnectTime = DateTime.Now; ClientFinished(client.IPPoint); //等待客户端发送来的数据 var state = new AsynSocketArg(); state.InitializeState(socket, heardLength, true); client.WaitForData(state); } catch (Exception ex) { OnSystemEvent(string.Format("客户端连接失败:{0}", ex)); } finally { allDone.Set(); } }