/// <summary> /// 这个方法当一个异步发送操作完成时被调用. /// </summary> /// <param name="e">Instance of SocketAsyncEventArgs.</param> private void ProcessSend(SocketAsyncEventArgs e) { AsyncSocketTokenEventArgs token = (AsyncSocketTokenEventArgs)e.UserToken; Interlocked.Add(ref this.totalBytesWrite, e.BytesTransferred); if (e.Count > this.bufferSize) { this.bufferManager.SetBuffer(e); } this.writePool.Push(e); e.UserToken = null; if (e.SocketError == SocketError.Success) { if (debug) { Debug.Write(string.Format("服务器总发送字节: {0}", e.BytesTransferred.ToString())); } this.RaiseEvent(this.DataSent, token); } else { this.RaiseDisconnectedEvent(token); } }
/// <summary> /// 这个方法在异步接收操作完成时调用. /// 如果远程主机关闭连接Socket将关闭 /// </summary> /// <param name="e">Instance of SocketAsyncEventArgs.</param> private void ProcessReceive(SocketAsyncEventArgs e) { AsyncSocketTokenEventArgs token = (AsyncSocketTokenEventArgs)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { Interlocked.Add(ref this.totalBytesRead, e.BytesTransferred); if (debug) { Debug.Write(string.Format("服务器总接收字节: {0}", this.totalBytesRead.ToString())); } token.SetReceivedBytesSize(e.BytesTransferred); this.RaiseEvent(this.DataReceived, token); try { if (token.Socket.Connected) { bool willRaiseEvent = token.Socket.ReceiveAsync(e); if (!willRaiseEvent) { this.ProcessReceive(e); } } } catch (ObjectDisposedException) { this.RaiseDisconnectedEvent(token); } catch (SocketException socketException) { if (socketException.ErrorCode == (int)SocketError.ConnectionReset) { this.RaiseDisconnectedEvent(token); } else { this.OnError(token, new AsyncSocketErrorEventArgs("异步接收数据发生异常!", socketException)); } } catch (Exception ex) { if (debug) { Debug.Write(string.Format(errorFormat, "AsyncSocketServer.ProcessReceive", ex.Source, ex.Message, ex.StackTrace, ex.ToString())); } } } else { this.RaiseDisconnectedEvent(token); } }
/// <summary> /// 引发断开连接事件 /// </summary> /// <param name="token">Instance of AsyncSocketTokenEventArgs.</param> private void RaiseDisconnectedEvent(AsyncSocketTokenEventArgs token) { if (null != token) { #if NET40 if (token.EndPoint != null) { AsyncSocketTokenEventArgs t; this.singleIPTokens.TryRemove(token.EndPoint.Address, out t); } AsyncSocketTokenEventArgs tt; if (this.tokens.TryRemove(token.ConnectionID, out tt)) { this.CloseClientSocket(token); if (null != token) { this.RaiseEvent(this.Disconnected, token); } } #else if (token.EndPoint != null) { lock (((ICollection)this.singleIPTokens).SyncRoot) { this.singleIPTokens.Remove(token.EndPoint.Address); } } lock (((ICollection)this.tokens).SyncRoot) { if (this.tokens.Remove(token.ConnectionID)) { this.CloseClientSocket(token); if (null != token) { this.RaiseEvent(this.Disconnected, token); } } } #endif } }
private void InitializePool() { this.bufferManager = new AsyncSocketEventArgsBufferManager(this.bufferSize * this.maxConnections * 2, this.bufferSize); this.readPool = new AsyncSocketEventArgsPool(); this.writePool = new AsyncSocketEventArgsPool(); #if NET40 this.tokens = new ConcurrentDictionary <Guid, AsyncSocketTokenEventArgs>(); this.singleIPTokens = new ConcurrentDictionary <IPAddress, AsyncSocketTokenEventArgs>(); #else this.tokens = new Dictionary <Guid, AsyncSocketTokenEventArgs>(); this.singleIPTokens = new Dictionary <IPAddress, AsyncSocketTokenEventArgs>(); #endif if (semaphore) { this.maxNumberAcceptedClients = new Semaphore(this.maxConnections, this.maxConnections); } this.bufferManager.InitBuffer(); SocketAsyncEventArgs readWriteEventArg; AsyncSocketTokenEventArgs token; // read Pool for (int i = 0; i < this.maxConnections; i++) { token = new AsyncSocketTokenEventArgs(); token.ReadEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(this.IO_Completed); this.bufferManager.SetBuffer(token.ReadEventArgs); token.SetBuffer(token.ReadEventArgs.Buffer, token.ReadEventArgs.Offset); this.readPool.Push(token.ReadEventArgs); } // write Pool for (int i = 0; i < this.maxConnections; i++) { readWriteEventArg = new SocketAsyncEventArgs(); readWriteEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(this.IO_Completed); readWriteEventArg.UserToken = null; this.bufferManager.SetBuffer(readWriteEventArg); this.writePool.Push(readWriteEventArg); } }
private void CloseClientSocket(AsyncSocketTokenEventArgs token) { try { if (token.Socket.Connected) { token.Socket.Shutdown(SocketShutdown.Both); token.Socket.Close(); } } catch (ObjectDisposedException) { if (debug) { Debug.Write("ObjectDisposedException"); } } catch (SocketException) { token.Socket.Close(); } catch (Exception e) { token.Socket.Close(); if (debug) { Debug.Write(string.Format(errorFormat, "AsyncSocketServer.CloseClientSocket", e.Source, e.Message, e.StackTrace, e.ToString())); } } finally { Interlocked.Decrement(ref this.numConnectedSockets); if (semaphore && !this.maxNumberAcceptedClients.SafeWaitHandle.IsClosed) { try { this.maxNumberAcceptedClients.Release(); } catch { } } if (debug) { Debug.Write(string.Format("有 {0} 个客户端已连接服务器!", this.numConnectedSockets.ToString())); } this.readPool.Push(token.ReadEventArgs); } }
/// <summary> /// 唤起事件 /// </summary> /// <param name="eventHandler">Instance of EventHandler.</param> /// <param name="eventArgs">Instance of AsyncSocketTokenEventArgs.</param> private void RaiseEvent(EventHandler <AsyncSocketTokenEventArgs> eventHandler, AsyncSocketTokenEventArgs eventArgs) { EventHandler <AsyncSocketTokenEventArgs> temp = Interlocked.CompareExchange(ref eventHandler, null, null); if (temp != null) { temp(this, eventArgs); } }