/// <summary> /// 协议第一个字节是协议标识,因此在接收到第一个字节的时候需要绑定协议解析对象 /// </summary> /// <param name="userToken"></param> private void BuildingSocketInvokeElement(AsyncSocketUserToken userToken) { byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset]; if (flag == (byte)ProtocolFlag.Upload) { userToken.AsyncSocketInvokeElement = new UploadSocketProtocol(this, userToken); } else if (flag == (byte)ProtocolFlag.Download) { userToken.AsyncSocketInvokeElement = new DownloadSocketProtocol(this, userToken); } else if (flag == (byte)ProtocolFlag.RemoteStream) { userToken.AsyncSocketInvokeElement = new RemoteStreamSocketProtocol(this, userToken); } else if (flag == (byte)ProtocolFlag.Throughput) { userToken.AsyncSocketInvokeElement = new ThroughputSocketProtocol(this, userToken); } else if (flag == (byte)ProtocolFlag.Control) { userToken.AsyncSocketInvokeElement = new ControlSocketProtocol(this, userToken); } else if (flag == (byte)ProtocolFlag.LogOutput) { userToken.AsyncSocketInvokeElement = new LogOutputSocketProtocol(this, userToken); } if (userToken.AsyncSocketInvokeElement != null) { Program.Logger.InfoFormat("Building socket invoke element {0}.Local Address: {1}, Remote Address: {2}", userToken.AsyncSocketInvokeElement, userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint); } }
public BaseSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_userName = ""; m_logined = false; m_socketFlag = ""; }
public void Add(AsyncSocketUserToken userToken) { lock (m_list) { m_list.Add(userToken); } }
public void Remove(AsyncSocketUserToken userToken) { lock (m_list) { m_list.Remove(userToken); } }
/// <summary> /// 当一个SocketAsyncEventArgs断开后,我们需要断开对应的Socket连接,并释放对应资源 /// </summary> /// <param name="userToken"></param> public void CloseClientSocket(AsyncSocketUserToken userToken) { if (userToken.ConnectSocket == null) { return; } string socketInfo = string.Format("Local Address: {0} Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint); Program.Logger.InfoFormat("Client connection disconnected. {0}", socketInfo); try { userToken.ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception E) { Program.Logger.ErrorFormat("CloseClientSocket Disconnect client {0} error, message: {1}", socketInfo, E.Message); } userToken.ConnectSocket.Close(); userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源 m_maxNumberAcceptedClients.Release(); m_asyncSocketUserTokenPool.Push(userToken); m_asyncSocketUserTokenList.Remove(userToken); }
/// <summary> /// NET底层IO线程也是每个异步事件都是由不同的线程返回到Completed事件, /// 因此在Completed事件需要对用户对象进行加锁, /// 避免同一个用户对象同时触发两个Completed事件。 /// </summary> /// <param name="sender"></param> /// <param name="asyncEventArgs"></param> void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs) { AsyncSocketUserToken userToken = asyncEventArgs.UserToken as AsyncSocketUserToken; userToken.ActiveDateTime = DateTime.Now; try { lock (userToken) {//避免同一个userToken同时有多个线程操作 if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive) { ProcessReceive(asyncEventArgs); } else if (asyncEventArgs.LastOperation == SocketAsyncOperation.Send) { ProcessSend(asyncEventArgs); } else { throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } } catch (Exception E) { Program.Logger.ErrorFormat("IO_Completed {0} error, message: {1}", userToken.ConnectSocket, E.Message); Program.Logger.Error(E.StackTrace); } }
private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { Program.Logger.InfoFormat("Client connection accepted. Local Address: {0}, Remote Address: {1}", acceptEventArgs.AcceptSocket.LocalEndPoint, acceptEventArgs.AcceptSocket.RemoteEndPoint); AsyncSocketUserToken userToken = m_asyncSocketUserTokenPool.Pop(); m_asyncSocketUserTokenList.Add(userToken); //添加到正在连接列表 userToken.ConnectSocket = acceptEventArgs.AcceptSocket; userToken.ConnectDateTime = DateTime.Now; try { bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { lock (userToken) { ProcessReceive(userToken.ReceiveEventArgs); } } } catch (Exception E) { Program.Logger.ErrorFormat("Accept client {0} error, message: {1}", userToken.ConnectSocket, E.Message); Program.Logger.Error(E.StackTrace); } StartAccept(acceptEventArgs); //把当前异步事件释放,等待下次连接 }
public void CopyList(ref AsyncSocketUserToken[] array) { lock (m_list) { array = new AsyncSocketUserToken[m_list.Count]; m_list.CopyTo(array); } }
/// <summary> /// 接收事件响应函数,接收的逻辑 /// </summary> /// <param name="receiveEventArgs"></param> private void ProcessReceive(SocketAsyncEventArgs receiveEventArgs) { AsyncSocketUserToken userToken = receiveEventArgs.UserToken as AsyncSocketUserToken; if (userToken.ConnectSocket == null) { return; } userToken.ActiveDateTime = DateTime.Now; if (userToken.ReceiveEventArgs.BytesTransferred > 0 && userToken.ReceiveEventArgs.SocketError == SocketError.Success) { int offset = userToken.ReceiveEventArgs.Offset; int count = userToken.ReceiveEventArgs.BytesTransferred; if ((userToken.AsyncSocketInvokeElement == null) & (userToken.ConnectSocket != null)) //存在Socket对象,并且没有绑定协议对象,则进行协议对象绑定 { BuildingSocketInvokeElement(userToken); offset = offset + 1; count = count - 1; } if (userToken.AsyncSocketInvokeElement == null) //如果没有解析对象,提示非法连接并关闭连接 { Program.Logger.WarnFormat("Illegal client connection. Local Address: {0}, Remote Address: {1}", userToken.ConnectSocket.LocalEndPoint, userToken.ConnectSocket.RemoteEndPoint); CloseClientSocket(userToken); } else { if (count > 0) //处理接收数据 { if (!userToken.AsyncSocketInvokeElement.ProcessReceive(userToken.ReceiveEventArgs.Buffer, offset, count)) { //如果处理数据返回失败,则断开连接 CloseClientSocket(userToken); } else //否则投递下次介绍数据请求 { bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { ProcessReceive(userToken.ReceiveEventArgs); } } } else { bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //投递接收请求 if (!willRaiseEvent) { ProcessReceive(userToken.ReceiveEventArgs); } } } } else { CloseClientSocket(userToken); } }
public UploadSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "Upload"; m_fileName = ""; m_fileStream = null; lock (m_asyncSocketServer.UploadSocketProtocolMgr) { m_asyncSocketServer.UploadSocketProtocolMgr.Add(this); } }
/// <summary> /// /// </summary> /// <param name="item"></param> public void Push(AsyncSocketUserToken item) { if (item == null) { throw new ArgumentException("Items added to a AsyncSocketUserToken cannot be null"); } lock (m_pool) {//对m_asyncSocketUserTokenPool和m_asyncSocketUserTokenList进行处理的时候都有加锁 m_pool.Push(item); } }
public LogOutputSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "LogOutput"; m_logFixedBuffer = new LogFixedBuffer(); lock (Program.AsyncSocketSvr.LogOutputSocketProtocolMgr) { Program.AsyncSocketSvr.LogOutputSocketProtocolMgr.Add(this); } SendResponse(); }
/// <summary> /// 按照连接数建立读写对象 /// </summary> public void Init() { AsyncSocketUserToken userToken; for (int i = 0; i < m_numConnections; i++) { userToken = new AsyncSocketUserToken(m_receiveBufferSize); userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); userToken.SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); m_asyncSocketUserTokenPool.Push(userToken); } }
public DownloadSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "Download"; m_fileName = ""; m_fileStream = null; m_sendFile = false; m_packetSize = 64 * 1024; lock (m_asyncSocketServer.DownloadSocketProtocolMgr) { m_asyncSocketServer.DownloadSocketProtocolMgr.Add(this); } }
public AsyncSocketInvokeElement(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) { m_asyncSocketServer = asyncSocketServer; m_asyncSocketUserToken = asyncSocketUserToken; m_netByteOrder = false; m_incomingDataParser = new IncomingDataParser(); m_outgoingDataAssembler = new OutgoingDataAssembler(); m_sendAsync = false; m_connectDT = DateTime.UtcNow; m_activeDT = DateTime.UtcNow; }
/// <summary> /// 发送事件响应函数,发送的逻辑,把发送数据放到一个列表中,当上一个发送事件完成响应Completed事件, /// 这时我们需要检测发送队列中是否存在未发送的数据,如果存在则继续发送 /// </summary> /// <param name="sendEventArgs"></param> /// <returns></returns> private bool ProcessSend(SocketAsyncEventArgs sendEventArgs) { AsyncSocketUserToken userToken = sendEventArgs.UserToken as AsyncSocketUserToken; if (userToken.AsyncSocketInvokeElement == null) { return(false); } userToken.ActiveDateTime = DateTime.Now; if (sendEventArgs.SocketError == SocketError.Success) { return(userToken.AsyncSocketInvokeElement.SendCompleted()); //调用子类回调函数 } else { CloseClientSocket(userToken); return(false); } }
public ControlSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "Control"; }
public ThroughputSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "Throughput"; }
public RemoteStreamSocketProtocol(AsyncSocketServer asyncSocketServer, AsyncSocketUserToken asyncSocketUserToken) : base(asyncSocketServer, asyncSocketUserToken) { m_socketFlag = "RemoteStream"; m_fileStream = null; }