/// <summary> /// 添加新客户 /// </summary> /// <param name="acceptEventArgs"></param> private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { if (acceptEventArgs.AcceptSocket.RemoteEndPoint == null) { throw new Exception("服务器停止."); } DelegateState.ServerStateInfo(" TCP - 客户端:" + acceptEventArgs.AcceptSocket.RemoteEndPoint + "连接"); DelegateState.ServerConnStateInfo(acceptEventArgs.AcceptSocket.RemoteEndPoint.ToString(), "TCP"); SocketUserToken userToken = m_asyncSocketUserTokenPool.Pop(); m_asyncSocketUserList.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) { DelegateState.ServerStateInfo("连接端 " + userToken.ConnectSocket + " 错误, 错误信息: " + e.Message); } StartAccept(acceptEventArgs);//递归继续异步监控客户端 }
/// <summary> /// 异步发送及接收回调函数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void IO_Completed(object sender, SocketAsyncEventArgs asyncEventArgs) { SocketUserToken userToken = asyncEventArgs.UserToken as SocketUserToken; userToken.ActiveDateTime = DateTime.Now; try { lock (userToken) { if (asyncEventArgs.LastOperation == SocketAsyncOperation.Receive) { ProcessReceive(asyncEventArgs); } else if (asyncEventArgs.LastOperation == SocketAsyncOperation.Send) { ProcessSend(asyncEventArgs); } else { throw new ArgumentException("最后一次操作完成套接字接收或发送"); } } } catch (Exception ex) { DelegateState.ServerStateInfo("异步发送及接收回调函数: IO_Completed " + userToken.ConnectSocket + " error, message: " + ex.Message); } }
/// <summary> /// 清除客户端 /// </summary> /// <param name="userToken"></param> public void CloseClientSocket(SocketUserToken userToken) { if (userToken.ConnectSocket == null) { return; } DelegateState.ReomveTCPStateInfo(userToken); string socketInfo = string.Format(" 删除地址: {0}", userToken.ConnectSocket.RemoteEndPoint); try { userToken.SendUserTokenAll.Clear();//清除设备连接 userToken.ConnectSocket.Shutdown(SocketShutdown.Both); } catch (Exception E) { DelegateState.ServerStateInfo("断开连接 " + socketInfo + " error, message: {1}" + E.Message); } userToken.LoginFlag = false; userToken.ConnectSocket.Close(); userToken.ConnectSocket = null; //释放引用,并清理缓存,包括释放协议对象等资源 serverconfig.semap.Release(); //增加个一信号量 m_asyncSocketUserTokenPool.Push(userToken); AsyncSocketUserList.Remove(userToken); }
/// <summary> /// 添加用户 /// </summary> /// <param name="userToken">用户信息</param> public void Add(SocketUserToken userToken) { lock (m_userlist) { m_userlist.Add(userToken); } }
/// <summary> /// 删除一个用户SocketUserToken /// </summary> /// <param name="userToken">SocketUserToken</param> public void Remove(SocketUserToken userToken) { lock (m_Devicelist) { m_Devicelist.Remove(userToken); } }
/// <summary> /// 复制给SocketUserToken[] /// </summary> /// <param name="array">ref SocketUserToken[]</param> public void CopyList(ref SocketUserToken[] array) { lock (m_Devicelist) { array = new SocketUserToken[m_Devicelist.Count]; m_Devicelist.CopyTo(array); } }
/// <summary> /// 把 SocketUserToken =null 的重新取出来加入列队 /// </summary> /// <param name="item">SocketUserToken</param> public void Push(SocketUserToken item) { if (item == null) { throw new ArgumentException("项目的用户不能为空!"); } lock (m_pool) { m_pool.Push(item); } }
/// <summary> /// 异步接收请求 /// </summary> /// <param name="socketAsyncEventArgs"></param> private void ProcessReceive(SocketAsyncEventArgs socketAsyncEventArgs) { SocketUserToken userToken = socketAsyncEventArgs.UserToken as SocketUserToken; 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.InvokeElement == null) & (userToken.ConnectSocket != null)) // 第一次发送的数据为-初始话是登录模式 还是 信息模式 { BuildingInvokeElement(userToken); // offset = offset + 1; // count = count - 1; } // userToken.InvokeElement = if (userToken.InvokeElement == null) //如果没有解析对象,提示非法连接并关闭连接 { DelegateState.ServerStateInfo("非法连接:" + userToken.ConnectSocket.RemoteEndPoint); CloseClientSocket(userToken); } else { if (count > 0) //处理接收数据 { if (!userToken.InvokeElement.ProcessReceive(userToken.ReceiveEventArgs.Buffer, offset, count)) //处理数据 { //如果处理数据返回失败,则断开连接 CloseClientSocket(userToken); } else { bool willRaiseEvent = userToken.ConnectSocket.ReceiveAsync(userToken.ReceiveEventArgs); //继续异步接收 if (!willRaiseEvent) { ProcessReceive(userToken.ReceiveEventArgs); } } } } } else { DelegateState.ServerStateInfo(string.Format("空数据,断线 {0}", userToken.ConnectSocket.RemoteEndPoint)); CloseClientSocket(userToken); } }
/// <summary> /// 初始化 /// </summary> /// <param name="asyncSocketServer"></param> /// <param name="socketUserToken"></param> public SocketInvokeElement(AsyncSocketServer asyncSocketServer, SocketUserToken socketUserToken) { m_asyncSocketServer = asyncSocketServer; m_socketUserToken = socketUserToken; m_outDataParser = new AssemblyOutDataParser(); m_InDataParser = new AssemblyInDataParser(); m_sendAsync = false; m_connectDT = DateTime.UtcNow; m_activeDT = DateTime.UtcNow; }
/// <summary> /// 异步发送回调函数 /// </summary> /// <param name="asyncEventArgs"></param> private bool ProcessSend(SocketAsyncEventArgs sendEventArgs) { SocketUserToken userToken = sendEventArgs.UserToken as SocketUserToken; userToken.ActiveDateTime = DateTime.Now; if (sendEventArgs.SocketError == SocketError.Success) { return(userToken.InvokeElement.SendCompleted(userToken)); //调用子类回调函数 } else { CloseClientSocket(userToken); return(false); } }
/// <summary> /// 初始化类,确定是登录或者发送信息 和其它的API /// </summary> /// <param name="userToken"></param> private void BuildingInvokeElement(SocketUserToken userToken) { //获取接收的0个字节-初始化是登录还是信息 byte flag = userToken.ReceiveEventArgs.Buffer[userToken.ReceiveEventArgs.Offset]; if (flag == (byte)ProtocolFlags.Login) { userToken.InvokeElement = new LoginSocketProtocol(this, userToken); } if (userToken.InvokeElement != null) { DelegateState.ServerStateInfo(userToken.ConnectSocket.RemoteEndPoint + "登录初始化"); } }
/// <summary> /// 初始化 /// </summary> /// <param name="asyncSocketServer"></param> /// <param name="socketUserToken"></param> public SocketInvokeElement(AsyncSocketServer asyncSocketServer, SocketUserToken socketUserToken) { m_asyncSocketServer = asyncSocketServer; m_socketUserToken = socketUserToken; m_outDataParser = new AssemblyOutDataParser(); m_InDataParser = new AssemblyInDataParser(); m_sendAsync = false; m_connectDT = DateTime.UtcNow; m_activeDT = DateTime.UtcNow; //InitMySql(); //m_saveDataThread = new Thread(saveDataFun); //m_saveDataThread.Start(); m_saveDataFileThread = new Thread(saveDataToFileFun); //利用构造函数,实例化一个线程,并且运行saveDataToFileFun函数 m_saveDataFileThread.Start(); //开启线程 }
/// <summary> /// 用户池初始化 /// </summary> public void Init() { Serverconfig = new ServerConfig(); m_asyncSocketUserList = new SocketUserClientList(); m_asyncSocketDeviceList = new SocketDeviceClientList(); m_asyncSocketUserTokenPool = new AsyncSocketUserPool(serverconfig.numConnections); SocketUserToken userToken; for (int i = 0; i < serverconfig.numConnections; i++) //按照连接数建立读写对象 { userToken = new SocketUserToken(serverconfig.buffSize); //异步回调函数初始化 userToken.ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); //异步回调函数初始化 userToken.SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); //开辟固定空间 m_asyncSocketUserTokenPool.Push(userToken); } }
/// <summary> /// 发送回调函数 /// </summary> /// <param name="userToken"></param> /// <returns></returns> public virtual bool SendCompleted(SocketUserToken userToken) { userToken.m_sendAsync = false; AsyncSendBufferManager asyncSendBufferManager = userToken.SendBuffer; asyncSendBufferManager.ClearFirstPacket(); //清除已发送的包 int offset = 0; int count = 0; if (asyncSendBufferManager.GetFirstPacket(ref offset, ref count))//缓存中是否还有数据没有发送,有就继续发送 { userToken.m_sendAsync = true; return(m_asyncSocketServer.SendAsyncEvent(userToken.ConnectSocket, userToken.SendEventArgs, asyncSendBufferManager.m_dynamicBufferManager.Buffer, offset, count)); } else { return(true); } }
/// <summary> /// 发送信息 /// </summary> /// <param name="commandText">string</param> /// <param name="userToken">SocketUserToken 连接客户端</param> /// <returns>bool</returns> public bool SendMsgClientMsg(string commandText, SocketUserToken userToken) { byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText); int totalLength = bufferUTF8.Length; //获取总大小 AsyncSendBufferManager asyncSendBufferManager = userToken.SendBuffer; asyncSendBufferManager.StartPacket(); asyncSendBufferManager.m_dynamicBufferManager.WriteBuffer(bufferUTF8); //写入命令内容 asyncSendBufferManager.EndPacket(); bool result = true; if (!userToken.m_sendAsync) { int packetOffset = 0; int packetCount = 0; if (asyncSendBufferManager.GetFirstPacket(ref packetOffset, ref packetCount)) { userToken.m_sendAsync = true; result = SendAsyncEvent(userToken.ConnectSocket, userToken.SendEventArgs, asyncSendBufferManager.m_dynamicBufferManager.Buffer, packetOffset, packetCount); } } return(result); }
/// <summary> /// 初始化 /// </summary> /// <param name="asyncSocketServer">AsyncSocketServer</param> /// <param name="socketUserToken">SocketUserToken</param> public MesgTransmitSocketProtocol(AsyncSocketServer asyncSocketServer, SocketUserToken socketUserToken) : base(asyncSocketServer, socketUserToken) { }
/// <summary> /// 初始化 /// </summary> /// <param name="asyncSocketServer">AsyncSocketServer</param> /// <param name="socketUserToken">SocketUserToken</param> public LoginSocketProtocol(AsyncSocketServer asyncSocketServer, SocketUserToken socketUserToken) : base(asyncSocketServer, socketUserToken) { }