private void StartWaitingForData(ClientConnection connection) { if (connection == null) { return; } if (connection.Buffer.Length <= 0) { return; } try { if (connection.Socket != null) { connection.Connected(); connection.Socket.BeginReceive(connection.Buffer, 0, connection.Buffer.Length, SocketFlags.None, new AsyncCallback(this.HandleIncomingData), connection); } } catch { } }
private void HandleConnection(IAsyncResult parameter) { if (parameter == null) { return; } ClientConnection connection = null; try { Socket socket = this.mListener.EndAccept(parameter); socket.NoDelay = true; socket.SendBufferSize = 1024 * 1024 * 1024; socket.IOControl(IOControlCode.KeepAliveValues, KeepaliveOptionValues, null); connection = new ClientConnection(socket); Interlocked.Increment(ref this.totle_count); connection.ConnectionId = this.totle_count; ClearInvalid(connection);//每次创建链接的时候要删除无效链接 lock (this.locker) { //if (this.mClientConnections.ContainsKey(connection.ConnectionId))//马勇增加的判断,如果已经存在这个关键值,则要求关闭这个已经存在的,并且删除 //{ // if (mClientConnections[connection.ConnectionId] != null) // { // mClientConnections[connection.ConnectionId].Socket.Close(); // } // mClientConnections.Remove(connection.ConnectionId); //} this.mClientConnections.Add(connection.ConnectionId, connection); connection.Connected(); } if (this.mOnConnected != null) { this.mOnConnected(this, new ZYBConnectedEventArgs(connection)); } this.StartWaitingForData(connection); } catch (ObjectDisposedException) { this.RaiseDisconnectedEvent(connection); } catch (SocketException exception) { this.RaiseErrorEvent(connection, exception); } finally { try { this.WaitForClient(); } catch (Exception) { } } }