protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new ManualExploreProxyConnection(clientInfo.Client, clientInfo.IsSecure, _trafficDataStore, "Sample Proxy Description", NetworkSettings)); }
private void OnEndReceiveCallback(IAsyncResult iar) { TcpClientInfo tcpClientInfo = iar.AsyncState as TcpClientInfo; var tcpClientSocket = tcpClientInfo.ClientSocket; try { int receivedCount = tcpClientSocket.EndReceive(iar); if (receivedCount <= 0) { throw new SocketException(); } var headerFactory = tcpClientInfo.HeaderFactory; headerFactory.PumpData(tcpClientInfo.Buffer, 0, receivedCount); string message; while (headerFactory.TryProcess(out message)) { RaiseMessageReceivedEvent( new NetworkConnection { Id = tcpClientInfo.Id, BelongListener = this }, message); } //Tiếp tục nhận dữ liệu tcpClientSocket.BeginReceive( tcpClientInfo.Buffer, 0, TcpClientInfo.BufferSize, SocketFlags.None, OnEndReceiveCallback, tcpClientInfo); } catch (SocketException ex) { //Khi có lỗi xảy ra rong quá trình nhận dữ liệu thì đóng kết nối string id = tcpClientInfo.Id; m_ClientConnections.Remove(id); tcpClientSocket.Close(); //Ném ra sự kiện đóng kết nối RaiseConnectionClosedEvent( new ConnectionClosedEventArgs { Connection = new NetworkConnection { Id = tcpClientInfo.Id, BelongListener = this } }); } catch (Exception ex) { Console.WriteLine("{0} Exception: \r\n {1}", Name, ex); } }
public void SendCommand(Command pCommand, TcpClientInfo pClient) { if (!IsRunning) { throw new InvalidOperationException("Cannot send commands while server is not running"); } m_server.Send(pClient, pCommand.ToByteArray()); }
private void AcceptTcpClientAsync() { try { tcpListener.BeginAcceptTcpClient(ar => { var tcpListener = ar.AsyncState as TcpListener; try { TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar); var ipAddress = string.Empty; tcpClient.ReceiveTimeout = configInfo.ReceiveTimeout; tcpClient.SendTimeout = configInfo.SendTimeout; KeepAliveHelper.SetKeepAlive(tcpClient.Client, 1000, 1000); ipAddress = tcpClient.Client.RemoteEndPoint.ToString().Split(':').First(); if (!tcpClientInfoDictionary.ContainsKey(ipAddress)) { var tcpClientInfo = new TcpClientInfo() { IPAddress = ipAddress, ComPort = new TcpClientWapper(tcpClient, loggerFactory) }; tcpClientInfoDictionary.Add(ipAddress, tcpClientInfo); } (tcpClientInfoDictionary[ipAddress].ComPort as TcpClientWapper).TcpClient = tcpClient; OnTcpClientAccepted(this, new TcpClientAcceptedEventArgs() { TcpClientInfo = tcpClientInfoDictionary[ipAddress] }); if (type == TcpListenerComPortType.One2One) { connectionStateChangedEventManager.StartMonitor(ConnectionStateChanged, this, tcpClient); } } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } AcceptTcpClientAsync(); }, tcpListener); } catch (Exception e) { loggerFactory?.GetLogger(Name).Error(e.ToString()); } }
/// <summary> /// Send a notification to a client /// </summary> /// <param name="pMessage">Message to be sent</param> /// <param name="pClient">Client to be notified</param> public void Notify(string pMessage, TcpClientInfo pClient) { if (!IsRunning) { throw new InvalidOperationException("Can't send a notification while server is not running"); } byte[] data = Command.PrefixCommand(CommandType.Notification, pMessage); m_server.Send(pClient, data); }
protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new TrafficStoreProxyConnection( _sourceStore, _matchMode, _ignoreAuth, clientInfo.Client, clientInfo.IsSecure, _saveStore, _proxyDescription)); }
/// <summary> /// Gets a connection /// </summary> /// <param name="clientInfo"></param> /// <returns></returns> protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new BinaryReverseProxyConnection(_forwardingHost, _forwardingPort, clientInfo.Client, clientInfo.IsSecure, _dataStore, NetworkSettings, Replacements)); /*if (_connection == null || _connection.Closed) * { * _connection = new BinaryReverseProxyConnection(_forwardingHost, _forwardingPort, * clientInfo.Client, clientInfo.IsSecure, _dataStore, NetworkSettings, Replacements); * } * return _connection;*/ }
private void btnSendFirst_Click(object sender, EventArgs e) { if (serverHandler.ConnectedClients == null || serverHandler.ConnectedClients.Count == 0) { return; } TcpClientInfo firstClient = serverHandler.ConnectedClients.ElementAt(0); var user = (UserInfo)firstClient.Tag; serverHandler.SendTo(firstClient, "Bonjour " + user.Name + "! Mouhahaha"); }
public void AutoReconnetTest() { tcpClient.Close(); tcpClientInfo = null; tcpClient = new TcpClient(); tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 8080); Thread.Sleep(500); Assert.IsNotNull(tcpClientInfo); }
public override void SendMessage(NetworkConnection connection, string message) { if (!m_ClientConnections.ContainsKey(connection.Id)) { return; } TcpClientInfo clientInfo = m_ClientConnections[connection.Id]; clientInfo.ClientSocket.Send( TcpHeaderFactory.ToPacket( Encoding.UTF8.GetBytes(message) )); }
public void OneTimeSetUp() { this.connectionState = false; this.tcpListenerComPort = new TcpListenerComPort(new TcpListenerComPortConfigInfo() { LocalIPAddress = "127.0.0.1", LocalPort = 8080, ReceiveTimeout = 500, SendTimeout = 500 }, TcpListenerComPortType.One2One, Substitute.For <ILoggerFactory>()); this.tcpListenerComPort.ConnectionStateChanged += (sender, e) => connectionState = e.IsConnected;; this.tcpListenerComPort.TcpClientAccepted += (sender, e) => tcpClientInfo = e.TcpClientInfo; this.tcpClient = new TcpClient(); }
/// <summary> /// Send a notification to all authenticated user except one /// </summary> /// <param name="pMessage">Message to be sent</param> /// <param name="pExclude">The user to exclude</param> public void NotifyAllAdmin(string pMessage, TcpClientInfo pExclude) { if (!IsRunning) { throw new InvalidOperationException("Can't send a notification while server is not running"); } foreach (var currClient in ConnectedClients) { if (currClient == pExclude) { continue; } User userInfo = (User)currClient.Tag; if (userInfo.IsLoggedIn) { Notify(pMessage, currClient); } } }
private void OnEndAccept(IAsyncResult iar) { Socket listenerSocket = iar.AsyncState as Socket; //Lưu client vào từ điển theo id string connectionId = NetworkConnection.GenerateId(); var clientSocket = listenerSocket.EndAccept(iar); var tcpClientInfo = new TcpClientInfo(connectionId, clientSocket); m_ClientConnections.Add(connectionId, tcpClientInfo); //Khởi tạo vòng nhận dữ liệu cho client clientSocket.BeginReceive( tcpClientInfo.Buffer, 0, TcpClientInfo.BufferSize, SocketFlags.None, OnEndReceiveCallback, tcpClientInfo); //Tiếp tục lắng nghe kết nối tiếp listenerSocket.BeginAccept(OnEndAccept, listenerSocket); //Raise Event NetworkConnection connection = new NetworkConnection { Id = connectionId, BelongListener = this, }; RaiseConnecionOpenedEvent(new ConnectionOpenedEventArgs { Connection = connection }); }
/// <summary> /// Gets a http connection that can trap requests and responses /// </summary> /// <param name="clientInfo"></param> /// <returns></returns> protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new AdvancedExploreProxyConnection(clientInfo.Client, clientInfo.IsSecure, TrafficDataStore, "Manual Explore", NetworkSettings, _trackRequestContext)); }
/// <summary> /// Gets a connection /// </summary> /// <param name="clientInfo"></param> /// <returns></returns> protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new TrackingReverseProxyConnection(clientInfo.Client, clientInfo.IsSecure, _dataStore, NetworkSettings, this)); }
public void SendTo(TcpClientInfo pClient, string pMessage) { byte[] data = Command.PrefixCommand(CommandType.Notification, pMessage); m_server.Send(pClient, data); }
/// <summary> /// Callback method for asynchronous accept operation. /// </summary> private void ProcessAccept() { TransportProvider<Socket> client = new TransportProvider<Socket>(); SocketAsyncEventArgs receiveArgs = null; TcpClientInfo clientInfo; try { if (CurrentState == ServerState.NotRunning) return; if (m_acceptArgs.SocketError != SocketError.Success) { // Error is unrecoverable. // We need to make sure to restart the // server before we throw the error. SocketError error = m_acceptArgs.SocketError; ThreadPool.QueueUserWorkItem(state => ReStart()); throw new SocketException((int)error); } // Process the newly connected client. client.Provider = m_acceptArgs.AcceptSocket; // Set up SocketAsyncEventArgs for receive operations. receiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(); receiveArgs.Completed += ReceiveHandler; // Return to accepting new connections. m_acceptArgs.AcceptSocket = null; if (!m_tcpServer.AcceptAsync(m_acceptArgs)) { ThreadPool.QueueUserWorkItem(state => ProcessAccept()); } #if !MONO // Authenticate the connected client Windows credentials. if (m_integratedSecurity) { NetworkStream socketStream = null; NegotiateStream authenticationStream = null; try { socketStream = new NetworkStream(client.Provider); authenticationStream = new NegotiateStream(socketStream); authenticationStream.AuthenticateAsServer(); if (authenticationStream.RemoteIdentity is WindowsIdentity) Thread.CurrentPrincipal = new WindowsPrincipal((WindowsIdentity)authenticationStream.RemoteIdentity); } finally { if (socketStream != null) socketStream.Dispose(); if (authenticationStream != null) authenticationStream.Dispose(); } } #endif if (MaxClientConnections != -1 && ClientIDs.Length >= MaxClientConnections) { // Reject client connection since limit has been reached. TerminateConnection(client, receiveArgs, false); } else { // We can proceed further with receiving data from the client. clientInfo = new TcpClientInfo() { Client = client, SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(), SendLock = new SpinLock(), SendQueue = new ConcurrentQueue<TcpServerPayload>() }; // Set up socket args. client.SetSendBuffer(SendBufferSize); clientInfo.SendArgs.Completed += m_sendHandler; clientInfo.SendArgs.SetBuffer(client.SendBuffer, 0, client.SendBufferSize); m_clientInfoLookup.TryAdd(client.ID, clientInfo); OnClientConnected(client.ID); if (!m_payloadAware) { receiveArgs.UserToken = client; } else { EventArgs<TransportProvider<Socket>, bool> userToken = ReusableObjectPool<EventArgs<TransportProvider<Socket>, bool>>.Default.TakeObject(); userToken.Argument1 = client; receiveArgs.UserToken = userToken; } ReceivePayloadAsync(client, receiveArgs); } } catch (Exception ex) { // Notify of the exception. if ((object)client.Provider != null) { string clientAddress = ((IPEndPoint)client.Provider.RemoteEndPoint).Address.ToString(); string errorMessage = string.Format("Unable to accept connection to client [{0}]: {1}", clientAddress, ex.Message); OnClientConnectingException(new Exception(errorMessage, ex)); } if ((object)receiveArgs != null) { TerminateConnection(client, receiveArgs, false); } } }
protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new CollectorAPIConnection(clientInfo.Client, clientInfo.IsSecure)); }
/// <summary> /// Gets a connection /// </summary> /// <param name="clientInfo"></param> /// <returns></returns> protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { return(new ReverseProxyConnection(_forwardingHost, _forwardingPort, clientInfo.Client, clientInfo.IsSecure, _dataStore, NetworkSettings, Replacements)); }
protected override IProxyConnection GetConnection(TcpClientInfo clientInfo) { _currentConnection = new MockProxyConnection(clientInfo.Client, clientInfo.IsSecure, _trafficDataStore, "Mock request", _mockSite); return(_currentConnection); }
public AuthenticationFeedbackArgs(AuthenticationResult pResult, TcpClientInfo pClient) { m_result = pResult; m_sender = pClient; }
/// <summary> /// Callback method for asynchronous accept operation. /// </summary> private void ProcessAccept(SocketAsyncEventArgs acceptArgs) { TransportProvider<Socket> client = new TransportProvider<Socket>(); SocketAsyncEventArgs receiveArgs = null; WindowsPrincipal clientPrincipal = null; TcpClientInfo clientInfo; try { if (CurrentState == ServerState.NotRunning) return; // If acceptArgs was disposed, m_acceptArgs will either // be null or another instance of SocketAsyncEventArgs. // This check will tell us whether it's been disposed. if ((object)acceptArgs != m_acceptArgs) return; if (acceptArgs.SocketError != SocketError.Success) { // Error is unrecoverable. // We need to make sure to restart the // server before we throw the error. SocketError error = acceptArgs.SocketError; ThreadPool.QueueUserWorkItem(state => ReStart()); throw new SocketException((int)error); } // Process the newly connected client. client.Provider = acceptArgs.AcceptSocket; client.Provider.ReceiveBufferSize = ReceiveBufferSize; // Set up SocketAsyncEventArgs for receive operations. receiveArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(); receiveArgs.Completed += ReceiveHandler; // Return to accepting new connections. acceptArgs.AcceptSocket = null; if (!m_tcpServer.AcceptAsync(acceptArgs)) { ThreadPool.QueueUserWorkItem(state => ProcessAccept(acceptArgs)); } #if !MONO // Authenticate the connected client Windows credentials. if (m_integratedSecurity) { NetworkStream socketStream = null; NegotiateStream authenticationStream = null; try { socketStream = new NetworkStream(client.Provider); authenticationStream = new NegotiateStream(socketStream); authenticationStream.AuthenticateAsServer(); if (authenticationStream.RemoteIdentity is WindowsIdentity) clientPrincipal = new WindowsPrincipal((WindowsIdentity)authenticationStream.RemoteIdentity); } catch (InvalidCredentialException) { if (!m_ignoreInvalidCredentials) throw; } finally { if (socketStream != null) socketStream.Dispose(); if (authenticationStream != null) authenticationStream.Dispose(); } } #endif if (MaxClientConnections != -1 && ClientIDs.Length >= MaxClientConnections) { // Reject client connection since limit has been reached. TerminateConnection(client, receiveArgs, false); } else { // We can proceed further with receiving data from the client. clientInfo = new TcpClientInfo { Client = client, SendArgs = FastObjectFactory<SocketAsyncEventArgs>.CreateObjectFunction(), SendLock = new object(), SendQueue = new ConcurrentQueue<TcpServerPayload>(), ClientPrincipal = clientPrincipal }; // Create operation to dump send queue payloads when the queue grows too large. clientInfo.DumpPayloadsOperation = new ShortSynchronizedOperation(() => { TcpServerPayload payload; // Check to see if the client has reached the maximum send queue size. if (m_maxSendQueueSize > 0 && clientInfo.SendQueue.Count >= m_maxSendQueueSize) { for (int i = 0; i < m_maxSendQueueSize; i++) { if (clientInfo.SendQueue.TryDequeue(out payload)) { payload.WaitHandle.Set(); payload.WaitHandle.Dispose(); payload.WaitHandle = null; } } throw new InvalidOperationException(string.Format("Client {0} connected to TCP server reached maximum send queue size. {1} payloads dumped from the queue.", clientInfo.Client.ID, m_maxSendQueueSize)); } }, ex => OnSendClientDataException(clientInfo.Client.ID, ex)); // Set up socket args. client.SetSendBuffer(SendBufferSize); clientInfo.SendArgs.Completed += m_sendHandler; clientInfo.SendArgs.SetBuffer(client.SendBuffer, 0, client.SendBufferSize); m_clientInfoLookup.TryAdd(client.ID, clientInfo); OnClientConnected(client.ID); if (!m_payloadAware) { receiveArgs.UserToken = client; } else { EventArgs<TransportProvider<Socket>, bool> userToken = FastObjectFactory<EventArgs<TransportProvider<Socket>, bool>>.CreateObjectFunction(); userToken.Argument1 = client; receiveArgs.UserToken = userToken; } ReceivePayloadAsync(client, receiveArgs); } } catch (ObjectDisposedException) { // m_acceptArgs may be disposed while in the middle of accepting a connection } catch (Exception ex) { // Notify of the exception. if ((object)client.Provider != null && (object)client.Provider.RemoteEndPoint != null) { string clientAddress = ((IPEndPoint)client.Provider.RemoteEndPoint).Address.ToString(); string errorMessage = string.Format("Unable to accept connection to client [{0}]: {1}", clientAddress, ex.Message); OnClientConnectingException(new Exception(errorMessage, ex)); } else { string errorMessage = string.Format("Unable to accept connection to client [unknown]: {0}", ex.Message); OnClientConnectingException(new Exception(errorMessage, ex)); } if ((object)receiveArgs != null) { TerminateConnection(client, receiveArgs, false); } } }