public void Bind(DeliveryConnection conn2) { this.connector = conn2; conn2.connector = this; this.Flush(); conn2.Flush(); }
void Delivery_OnDisconnected(DeliveryConnection conn) { // decrement the counter keeping track of the total number of clients connected to the server m_maxNumberAcceptedClients.Release(); ReceiveEventArgs_Release(conn.receiveEventArgs); connMap.TryRemove(conn.GetHashCode(), out _); //conn.Close(); }
public void Connect(Action <DeliveryConnection> onConneced) { try { //Logger.Info("[CL.DeliveryClient] Socket.Iocp,connecting... host:" + host + " port:" + port); //(x.1) Instantiates the endpoint and socket. var hostEndPoint = new IPEndPoint(NetHelp.ParseToIPAddress(host), port); var socket = new global::System.Net.Sockets.Socket(hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); DeliveryConnection _conn = new DeliveryConnection(); _conn.Conn_OnConnected = onConneced; var receiveEventArgs = _conn.receiveEventArgs = new SocketAsyncEventArgs(); receiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); receiveEventArgs.UserToken = _conn; _conn.Init(socket); //var buff= DataPool.BytesGet(receiveBufferSize); var buff = new byte[receiveBufferSize]; _conn.receiveEventArgs.SetBuffer(buff, 0, buff.Length); //(x.2) SocketAsyncEventArgs connectArgs = new SocketAsyncEventArgs(); connectArgs.RemoteEndPoint = hostEndPoint; connectArgs.Completed += new EventHandler <SocketAsyncEventArgs>(OnConnect); connectArgs.UserToken = _conn; socket.ConnectAsync(connectArgs); } catch (Exception ex) { Logger.Error(ex); } }
private DeliveryConnection Delivery_OnConnected(global::System.Net.Sockets.Socket socket) { var conn = new DeliveryConnection(); conn.Init(socket); conn.Conn_OnDisconnected = Delivery_OnDisconnected; connMap[conn.GetHashCode()] = conn; try { Conn_OnConnected?.Invoke(conn); } catch (Exception ex) { Logger.Error(ex); } return(conn); }
// This method is invoked when an asynchronous receive operation completes. // If the remote host closed the connection, then the socket is closed. // If data was received then the data is echoed back to the client. // private void ProcessReceive(SocketAsyncEventArgs e) { try { //读取数据 DeliveryConnection conn = (DeliveryConnection)e.UserToken; if (conn != null) { // check if the remote host closed the connection if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { //读取数据 conn.AppendData(new ArraySegment <byte>(e.Buffer, e.Offset, e.BytesTransferred)); //byte[] buffData = DataPool.BytesGet(receiveBufferSize); byte[] buffData = new byte[receiveBufferSize]; e.SetBuffer(buffData, 0, buffData.Length); // start loop //继续接收. 为什么要这么写,请看Socket.ReceiveAsync方法的说明 if (!conn.socket.ReceiveAsync(e)) { ProcessReceive(e); } } else { conn.Close(); } } } catch (Exception ex) { Logger.Error(ex); } }