public void Initialize() { _asyncUserToken = new AsyncUserToken(); _asyncUserToken.ReceiveSocketAsyncEventArgs.SetBuffer(new byte[BUFFER_SIZE], 0, BUFFER_SIZE); _asyncUserToken.ReceiveSocketAsyncEventArgs.Completed += IO_Completed; _asyncUserToken.SendSocketAsyncEventArgs.SetBuffer(new byte[BUFFER_SIZE], 0, 0); _asyncUserToken.SendSocketAsyncEventArgs.Completed += IO_Completed; var remoteIP = IPAddress.Parse(_remoteServerIP); var remotePort = int.Parse(_remoteServerPort); EndPoint remotEndPoint = new IPEndPoint(remoteIP, remotePort); _asyncUserToken.ReceiveSocketAsyncEventArgs.RemoteEndPoint = remotEndPoint; _asyncUserToken.SendSocketAsyncEventArgs.RemoteEndPoint = remotEndPoint; }
private void CloseClientSocket(AsyncUserToken asyncUserToken) { string clientIP = string.Empty; try { if (asyncUserToken.Socket != null) { clientIP = asyncUserToken.Socket.RemoteEndPoint.ToString(); asyncUserToken.Socket.Shutdown(SocketShutdown.Both); asyncUserToken.Socket.Close(); asyncUserToken.Socket = null; asyncUserToken.ReceiveSocketAsyncEventArgs.AcceptSocket = null; asyncUserToken.SendSocketAsyncEventArgs.AcceptSocket = null; } } catch (Exception ex) { _log.ErrorFormat("AsyncServerBase->CloseClientSocket出现异常{0}, clientIP = {1}", ex, clientIP); } asyncUserToken.Reset(); }
private AsyncUserToken GetAsyncUserToken(Socket clientSocket) { AsyncUserToken userToken = null; if (_asyncUserTokenPool.Count == 0) { userToken = new AsyncUserToken() { Socket = clientSocket }; userToken.ReceiveSocketAsyncEventArgs.SetBuffer(new byte[BUFFER_SIZE], 0, BUFFER_SIZE); userToken.ReceiveSocketAsyncEventArgs.AcceptSocket = clientSocket; userToken.ReceiveSocketAsyncEventArgs.Completed += IO_Completed; _asyncUserTokenPool.Add(userToken); } else { userToken = _asyncUserTokenPool[0]; } return(userToken); }
private void ProcessReceive(SocketAsyncEventArgs readEventArgs) { /*需要检查客户端是否关闭了连接*/ AsyncUserToken asyncUserToken = readEventArgs.UserToken as AsyncUserToken; try { if (readEventArgs.BytesTransferred > 0 && readEventArgs.SocketError == SocketError.Success) { Interlocked.Add(ref _totalBytesReceived, (long)readEventArgs.BytesTransferred); _log.Info(string.Format("目前已接受{0}字节的数据", _totalBytesReceived)); /*读取缓冲区中的数据*/ /*半包, 粘包*/ try { /*读取数据*/ byte[] dataTransfered = new byte[readEventArgs.BytesTransferred]; Array.Copy(readEventArgs.Buffer, readEventArgs.Offset, dataTransfered, 0, readEventArgs.BytesTransferred); asyncUserToken.ReceiveBuffer.AddRange(dataTransfered); /* 4字节包头(长度) + 包体*/ /* Header + Body */ /* 接收到的数据可能小于一个包的大小,需分多次接收 * 先判断包头的大小,够一个完整的包再处理 */ while (asyncUserToken.ReceiveBuffer.Count > DATA_CHUNK_LENGTH_HEADER) { /*判断包的长度*/ byte[] lenBytes = asyncUserToken.ReceiveBuffer.GetRange(0, DATA_CHUNK_LENGTH_HEADER).ToArray(); int bodyLen = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(lenBytes, 0)); //包体的长度 var packageLength = DATA_CHUNK_LENGTH_HEADER + bodyLen; //一个数据包的长度,4字节包头 + 包体的长度 var receivedLengthExcludeHeader = asyncUserToken.ReceiveBuffer.Count - DATA_CHUNK_LENGTH_HEADER; //去掉包头之后接收的长度 /*接收的数据长度不够时,退出循环,让程序继续接收*/ if (receivedLengthExcludeHeader < bodyLen) { break; } /*接收的数据长度大于一个包的长度时,则提取出来,交给后面的程序去处理*/ byte[] receivedBytes = asyncUserToken.ReceiveBuffer.GetRange(DATA_CHUNK_LENGTH_HEADER, bodyLen).ToArray(); asyncUserToken.ReceiveBuffer.RemoveRange(0, packageLength); /*从缓冲区重移出取出的数据*/ /*抽象数据处理方法,receivedBytes是一个完整的包*/ ProcessData(asyncUserToken, receivedBytes); } /*继续接收, 非常关键的一步*/ if (asyncUserToken.Socket != null && !asyncUserToken.Socket.ReceiveAsync(readEventArgs)) { ProcessReceive(readEventArgs); } } catch (Exception ex) { _log.ErrorFormat("Program->ProcessReceive出现异常, Exception = {0}", ex); } } else { CloseClientSocket(asyncUserToken); } } finally { } }