/// <summary> /// Listener 生成的 AsyncSocketClient 回调方法 /// </summary> /// <param name="listenParam">客户端参数</param> /// <param name="client">生成的客户端 实体类</param> private void Listener_OnAcceptSocketClient(ListenParam listenParam, AsyncSocketClient client) { try { lock (_clientGroup) { _clientGroup[client.ConnectSocket] = client; } //给Client添加消息处理事件 client.OnSocketClose += Client_OnSocketClose; client.OnReadData += Client_OnReadData; client.OnSendData += Client_OnSendData; client.OnSocketHeart += Client_OnSocketHeart; _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read)); var param = new SocketEventParam(client.ConnectSocket, EN_SocketEvent.accept) { ClientInfo = client.ClientInfo }; _socketEventPool.PutObj(param); } catch (Exception ex) { NetLogger.Log(@"Listener_OnAcceptSocket 异常", ex); } }
/// <summary> /// 作为客户端连接后要对AsyncSocketClient的处理--事件方法 /// </summary> /// <param name="param"></param> /// <param name="client"></param> private void SocketConnectEvent(SocketEventParam param, AsyncSocketClient client) { try { if (param.Socket == null || client == null) //连接失败 { } else { lock (_clientGroup) { _clientGroup[client.ConnectSocket] = client; } client.OnSocketClose += Client_OnSocketClose; client.OnReadData += Client_OnReadData; client.OnSendData += Client_OnSendData; _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read)); } _socketEventPool.PutObj(param); } catch (Exception ex) { NetLogger.Log($"SocketConnectEvent 异常 {ex.Message}***", ex); } }
/// <summary> /// 对读取到的数据进行处理--Client异步读取完后会执行这个事件方法 /// </summary> /// <param name="client">当前客户端类</param> /// <param name="readData">读取到的数据</param> private void Client_OnReadData(AsyncSocketClient client, byte[] readData, int offset, int count) { _listReadEvent.PutObj(new SocketEventDeal(client, EN_SocketDealEvent.read)); //读下一条 try { var param = new SocketEventParam(client.ConnectSocket, EN_SocketEvent.read) { ClientInfo = client.ClientInfo, Data = readData, Offset = offset, Count = count }; if (client.ConnectSocket.Connected) { _socketEventPool.PutObj(param); lock (this) { ReadByteCount += readData.Length; } } } catch (Exception ex) { NetLogger.Log($@"Client_OnReadData 异常 {ex.Message}***{ex.StackTrace}"); } }
// 每秒可以起送应对几千个客户端连接。接收对方监听采用AcceptAsync,也是异步操作。有单独的线程负责处理Accept。 // 线程会同时投递多个AcceptAsync,就是已经建立好多个socket,等待客户端连接。当客户端到达时,可以迅速生成可用socket。 /// <summary> /// 处理新的连接 /// </summary> private void DealNewAccept() { try { //维持10个并发监听listener if (AcceptAsyncCount <= 10) { StartAccept(); } //检查新的Client是不是有问题 while (true) { _newSocketClientQueue.TryDequeue(out AsyncSocketClient client); if (client == null) { break; } DealNewAccept(client); } } catch (Exception ex) { NetLogger.Log($@"DealNewAccept 异常", ex); } }
public void OnConnectorDisconnectHandler(object sender, object disconnectionState) { IConnector connector = sender as IConnector; if (connector == null) { return; } connector.DisconnectEvent -= OnConnectorDisconnectHandler; TeamPainterTCPClient client = null; lock (_cSync) { long clientID; _clientConnectionAssociation.TryGetAndRemove(connector.UniqueID, out clientID); _clients.TryGetAndRemove(clientID, out client); } if (client != null) { client.Connector.DisconnectEvent -= OnConnectorDisconnectHandler; client.Connector.ReceiveAction -= OnReceveDataHandler; client.Connector.ReceiveComAction -= OnReceiveCommandHandler; } NetLogger.Log(connector.UniqueID + " is disconnected"); DisconnectEvent?.Invoke(client, disconnectionState); }
private void OnConnectCallback(IAsyncResult ar) { Socket sock = (Socket)ar.AsyncState; if (sock == null) return; IPEndPoint ep = null; try { sock.EndConnect(ar); ep = sock.RemoteEndPoint as IPEndPoint; _TCP = new ATCPConnector(sock, Uid64.CreateNewSync().Data, NetHelper.READ_BUFFER_BIG); _TCP.DisconnectEvent += OnDisconnectEventHandler; _TCP.ReceiveAction += OnReceveDataHandler; _TCP.ReceiveComAction += OnReceiveCommandHandler; } catch (SocketException ex){ sock.Close(); sock = null; NetLogger.Log(ex); return; } _isActive = true; if (ep != null) { NetLogger.Log("Connected to " + sock.RemoteEndPoint); } ConnectEvent?.Invoke(this, _TCP); }
/// <summary> /// 开始监听 /// </summary> /// <param name="listenFault">监听失败的端口集合</param> /// <returns>true,存在监听失败的端口,false,反之</returns> public bool StartListen(out List <int> listenFault) { ServerStart = true; _clientPacketManage = new ClientPacketManage(this); _clientPacketManage.OnSocketPacketEvent += PutClientPacket; _netConnectManage.OnSocketConnectEvent += SocketConnectEvent; _listenerList.Clear(); Task.Run(() => NetReadProcess()); Task.Run(() => NetSendProcess()); Task.Run(() => NetPacketProcess()); listenFault = new List <int>(); foreach (ListenParam param in _listListenPort) { NetListener listener = new NetListener(this); listener.ListenParam = param; listener.OnAcceptSocket += Listener_OnAcceptSocketClient; //返回Listener生成的 AsyncSocketClient if (!listener.StartListen()) { listenFault.Add(param.Port); } else { _listenerList.Add(listener); NetLogger.Log($@"监听成功!端口:{param.Port}"); } } return(listenFault.Count == 0); }
private void OnReceiveCommandHandler(IConnector connector, ICommandArg arg) { try { if (connector != null) { _commands.Execute(connector, arg); } } catch (Exception ex) { NetLogger.Log(ex, LogType.Exception); } }
private void OnReceveDataHandler(IConnector connector, byte[] data) { try { if (connector != null) { _commands.Execute(connector, data); } } catch (Exception ex) { NetLogger.Log(ex.ToString(), LogType.Exception); } }
public void Disconnect() { if (_TCP == null){ NetLogger.Log("TCP connection module is not connected"); return; } _TCP.Disconnect(); }
private void OnStartListener(object sender, EventArgs arg) { NetLogger.Log("TCP host start listening at" + _autorizator.Listener.ListenAddress); tbPort.Invoke((MethodInvoker) delegate { tbPort.ReadOnly = true; }); tbIP.Invoke((MethodInvoker) delegate { tbIP.ReadOnly = true; }); btnStartStop.Invoke((MethodInvoker) delegate { btnStartStop.Text = "Stop"; }); pnlIndicator.Invoke((MethodInvoker) delegate { pnlIndicator.BackColor = Color.LimeGreen; }); btnSettings.Invoke((MethodInvoker) delegate { btnSettings.Enabled = false; }); }
/// <summary> /// 给某个客户端发送消息 /// </summary> /// <param name="socket"></param> /// <param name="data">数据</param> /// <returns></returns> public EN_SendDataResult SendData(Socket socket, byte[] data) { if (socket != null) { return(_netServer.SendData(socket, data)); } NetLogger.Log(@"还没连接!"); return(EN_SendDataResult.no_client); }
public void SendDataEx(Socket socket, byte[] data) { if (socket != null) { _netServer.SendData(socket, data); return; } NetLogger.Log(@"还没连接!"); }
private void OnStopListener(object sender, object stopState) { _autorizator.Stop(); _worker.Stop(); NetLogger.Log("TCP host stop listening"); tbPort.Invoke((MethodInvoker) delegate { tbPort.ReadOnly = false; }); tbIP.Invoke((MethodInvoker) delegate { tbIP.ReadOnly = false; }); btnStartStop.Invoke((MethodInvoker) delegate { btnStartStop.Text = "Start"; }); pnlIndicator.Invoke((MethodInvoker) delegate { pnlIndicator.BackColor = Color.Red; }); btnSettings.Invoke((MethodInvoker) delegate { btnSettings.Enabled = true; }); }
public void Connect(object connectParam) { if (_isActive){ NetLogger.Log("TCP client is already connected"); return; } IPEndPoint endPoint = connectParam as IPEndPoint; if (endPoint == null){ throw new ArgumentNullException("Incorrect connect param"); } Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.BeginConnect(endPoint, OnConnectCallback, sock); }
/// <summary> /// 客户端连接成功回调事件方法 /// </summary> /// <param name="sender"></param> /// <param name="acceptEventArgs"></param> private void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs acceptEventArgs) { try { Interlocked.Decrement(ref AcceptAsyncCount); _acceptEvent.Set(); acceptEventArgs.Completed -= AcceptEventArg_Completed; ProcessAccept(acceptEventArgs); } catch (Exception ex) { NetLogger.Log($@"AcceptEventArg_Completed {ex.Message}", ex); } }
private void Client_OnSocketClose(AsyncSocketClient client) { try { SocketEventParam param = new SocketEventParam(client.ConnectSocket, EN_SocketEvent.close); param.ClientInfo = client.ClientInfo; //Console.WriteLine("放入关闭命令"); _socketEventPool.PutObj(param); } catch (Exception ex) { NetLogger.Log($"Client_OnSocketClose 异常 {ex.Message}***", ex); } }
/// <summary> /// 发送消息 /// </summary> private void NetSendProcess() { while (true) { try { DealSendEvent(); _listSendEvent.WaitOne(1000); } catch (Exception ex) { NetLogger.Log($@"Error", ex); } } }
private void NCCreateNewPictureBox(IConnector connection, ArgNewPictureBox arg) { long clientFakePBID = arg.PictureBoxID; long realEditablePBID = Uid64.CreateNew().Data; arg.PictureBoxID = realEditablePBID; lock (_npbSync) { _newPB.Enqueue(arg.PictureBoxID, arg); _clientServerPictureBoxID[clientFakePBID] = realEditablePBID; } lock (_astSync) { _argsSendToAllClients.Add(arg); } NetLogger.Log("CreatePB from: " + clientFakePBID + " to " + realEditablePBID); }
/// <summary> /// 对收到的数据进行处理 /// </summary> private void NetPacketProcess() { while (ServerStart) { try { _socketEventPool.WaitOne(1000); DealEventPool(); } catch (Exception ex) { NetLogger.Log($@"DealEventPool 异常 {ex.Message}***{ex.StackTrace}"); } } }
private void OnDisconnectEventHandler(object sender, object disconnectState) { _TCP.DisconnectEvent -= OnDisconnectEventHandler; _TCP.ReceiveAction -= OnReceveDataHandler; _TCP.ReceiveComAction -= OnReceiveCommandHandler; _clientID = 0; _isActive = false; string s = "Disconnected "; if (disconnectState != null) { s += disconnectState.ToString(); } NetLogger.Log(s); DisconnectEvent?.Invoke(_TCP, disconnectState); _TCP = null; }
/// <summary> /// 收到最终的字节流 事件方法 /// </summary> /// <param name="socketParam"></param> private void SocketPacketDeal(SocketEventParam socketParam) { string peerIp = socketParam.ClientInfo.PeerRemoteEndPoint; switch (socketParam.SocketEvent) { case EN_SocketEvent.accept: { AddClient(socketParam); NetLogger.Log($@"客户端链接!本地端口:{socketParam.ClientInfo.LocalPort},对端:{peerIp},客户端数量:{ClientCount}"); break; } case EN_SocketEvent.close: { RemoveClient(socketParam); NetLogger.Log($@"客户端断开!本地端口:{socketParam.ClientInfo.LocalPort},对端:{peerIp},剩余客户端数量:{ClientCount}"); break; } case EN_SocketEvent.read: { var data = new byte[socketParam.Count]; Array.Copy(socketParam.Data, 0, data, 0, socketParam.Count); OnSocketReceive?.Invoke(socketParam.Socket, data); break; } case EN_SocketEvent.connect: { if (socketParam.Socket != null) { AddClient(socketParam); NetLogger.Log($@"连接对端成功!本地端口:{socketParam.ClientInfo.LocalPort},对端:{peerIp},客户端数量:{ClientCount}"); } else { NetLogger.Log($@"连接对端失败!本地端口:{socketParam.ClientInfo.LocalPort},对端:{peerIp},客户端数量:{ClientCount}"); } break; } } //SocketEventParamPool.Instance.PushSocketEventDeal(socketParam); }
// Cleanup public void Close() { if (NetLogger.On) { NetLogger.Log("Closing UdpSocket on " + Port); } Closed = true; CancellationTokenSource.Cancel(); try { UdpClient.Close(); UdpClient.Dispose(); } catch { } }
private void NCReceiveClientID(IConnector connector, ArgUniqueID arg) { if (arg == null) { return; } _netClient.ClientID = arg.UniqueID; NetLogger.Log("Login success, received client ID: " + arg.UniqueID); pnlFile.Invoke((MethodInvoker) delegate { pnlFile.Enabled = true; }); pnlTools.Invoke((MethodInvoker) delegate { pnlTools.Enabled = true; }); rbtnBrush.Invoke((MethodInvoker) delegate { rbtnBrush.Checked = true; }); if (_trafficForm != null) { _trafficForm.Invoke((MethodInvoker) delegate { _trafficForm.Text = "Client: " + _netClient.ClientID.ToString(); }); } }
private void OnNewTCPConnectionEventHandler(object sender, IConnector connector) { if (connector == null) { return; } lvClients.Invoke((MethodInvoker) delegate { ListViewItem lvi = new ListViewItem(connector.UniqueID.ToString()); lvi.Name = connector.UniqueID.ToString(); lvi.SubItems.Add("No autorized"); lvi.BackColor = Color.DarkGray; lvi.ForeColor = Color.WhiteSmoke; lvClients.Items.Add(lvi); }); NetLogger.Log(connector.UniqueID + " is connected"); }
/// <summary> /// 根据连接请求建立AsyncSocketClient /// </summary> /// <param name="acceptEventArgs"></param> private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { try { using (acceptEventArgs) { if (acceptEventArgs.AcceptSocket != null) { AsyncSocketClient client = new AsyncSocketClient(acceptEventArgs.AcceptSocket); client.CreateClientInfo(this); _newSocketClientQueue.Enqueue(client); _acceptEvent.Set(); } } } catch (Exception ex) { NetLogger.Log($@"ProcessAccept {ex.Message}***", ex); } }
/// <summary> /// 开始监听 /// </summary> /// <returns></returns> public bool StartListen() { try { _start = true; IPEndPoint listenPoint = new IPEndPoint(IPAddress.Any, ListenParam.Port); _listenSocket = new Socket(listenPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(listenPoint); _listenSocket.Listen(200); Task.Run(() => NetProcess()); //维持多个监听Socket并行监听客户端请求 StartAccept(); return(true); } catch (Exception ex) { NetLogger.Log($@"**监听异常!{ex.Message}"); return(false); } }
/// <summary> /// 收到包长度异常的时间方法 /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="offset"></param> /// <param name="packetLen"></param> internal void OnRcvPacketLenError(Socket socket, byte[] buffer, int offset, int packetLen) { try { lock (_clientGroup) { if (!_clientGroup.Keys.Any(a => a == socket)) { Debug.Assert(false); return; } AsyncSocketClient client = _clientGroup[socket]; client.CloseSocket(); } } catch (Exception ex) { NetLogger.Log("OnRcvPacketLenError 异常", ex); } }
public void OnConnectorDisconnectHandler(object sender, object disconnectionState) { IConnector connector = sender as IConnector; if (connector == null) { return; } connector.DisconnectEvent -= OnConnectorDisconnectHandler; connector.ReceiveAction -= OnReceveDataHandler; connector.ReceiveComAction -= OnReceiveCommandHandler; lock (_cSync) { _connectors.Remove(connector.UniqueID); } NetLogger.Log(connector.UniqueID + " disconneted. " + (disconnectionState == null ? "" : disconnectionState.ToString())); DisconnectEvent?.Invoke(connector, disconnectionState); }
public bool AddClient(TeamPainterTCPClient client) { if (client == null || client.Connector == null) { return(false); } long connectionID = client.Connector.UniqueID; lock (_cSync) { TeamPainterTCPClient regcl; _clients.TryGetValue(client.UniqueID, out regcl); if (regcl != null) { NetLogger.Log("This client is already exist"); return(false); } if (_clients.Count >= _maxClients) { NetLogger.Log("Max connection"); return(false); } _clientConnectionAssociation[connectionID] = client.UniqueID; _clients[client.UniqueID] = client; client.Connector.DisconnectEvent += OnConnectorDisconnectHandler; client.Connector.ReceiveAction = null; client.Connector.ReceiveAction += OnReceveDataHandler; client.Connector.ReceiveComAction = null; client.Connector.ReceiveComAction += OnReceiveCommandHandler; return(true); } }