static void Main(string[] args) { Configuration .Create() .UseAutofac() .RegisterCommonComponents() .UseLog4Net(); var sendReply = true; int totalHandled = 0; Stopwatch watch = null; var serverEndPoint = new IPEndPoint(SocketUtils.GetLocalIPV4(), 5000); var serverListener = new TcpServerListener(serverEndPoint, null, (connection, message, sendReplyAction) => { var local = Interlocked.Increment(ref totalHandled); if (local == 1) { watch = Stopwatch.StartNew(); } if (local % 10000 == 0) { Console.WriteLine("received message, size:" + message.Length + ", count:" + local + ", timeSpent:" + watch.ElapsedMilliseconds + "ms"); } if (sendReply) { sendReplyAction(message); } }); serverListener.Start(); Console.ReadLine(); }
public TcpService(IPublisher publisher, IPEndPoint serverEndPoint, IPublisher networkSendQueue, TcpServiceType serviceType, TcpSecurityType securityType, Func <Guid, IPEndPoint, ITcpDispatcher> dispatcherFactory, TimeSpan heartbeatInterval, TimeSpan heartbeatTimeout, IAuthenticationProvider authProvider, X509Certificate certificate, int connectionPendingSendBytesThreshold) { Ensure.NotNull(publisher, "publisher"); Ensure.NotNull(serverEndPoint, "serverEndPoint"); Ensure.NotNull(networkSendQueue, "networkSendQueue"); Ensure.NotNull(dispatcherFactory, "dispatcherFactory"); Ensure.NotNull(authProvider, "authProvider"); if (securityType == TcpSecurityType.Secure) { Ensure.NotNull(certificate, "certificate"); } _publisher = publisher; _serverEndPoint = serverEndPoint; _serverListener = new TcpServerListener(_serverEndPoint); _networkSendQueue = networkSendQueue; _serviceType = serviceType; _securityType = securityType; _dispatcherFactory = dispatcherFactory; _heartbeatInterval = heartbeatInterval; _heartbeatTimeout = heartbeatTimeout; _connectionPendingSendBytesThreshold = connectionPendingSendBytesThreshold; _authProvider = authProvider; _certificate = certificate; }
public ServerTcp() { connectedClients = new List <SimpleTcpClient>(); listener = new TcpServerListener(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000)); listener.OnConnectionAccepted += Listener_OnConnectionAccepted; listener.OnException += Listener_OnException; listener.Start(); }
public void Dispose() { if (!State) { TcpServerListener.Stop(); GC.SuppressFinalize(this); } }
public TcpService(IPublisher publisher, IPEndPoint serverEndPoint) { Ensure.NotNull(publisher, "publisher"); Ensure.NotNull(serverEndPoint, "serverEndPoint"); _publisher = publisher; _serverEndPoint = serverEndPoint; _tcpDispatcher = new ClientTcpDispatcher(); _serverListener = new TcpServerListener(_serverEndPoint); }
public TcpServerListenerTest() { // Start the server with a simple 'Increase by one' handler m_Target = new TcpServerListener(request => { // Increase each byte by one for (int i = 0; i < request.Length; ++i) { ++request[i]; } return(request); }); m_Target.Start(IPAddress.Loopback, 8000); }
public void should_connect_to_each_other_and_send_data() { var serverEndPoint = new IPEndPoint(_ip, _port); X509Certificate cert = GetServerCertificate(); var sent = new byte[1000]; new Random().NextBytes(sent); var received = new MemoryStream(); var done = new ManualResetEventSlim(); var listener = new TcpServerListener(serverEndPoint); listener.StartListening((endPoint, socket) => { var ssl = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(), endPoint, socket, cert, delegate { return(true, null); }, verbose: true); ssl.ConnectionClosed += (x, y) => done.Set(); if (ssl.IsClosed) { done.Set(); } Action <ITcpConnection, IEnumerable <ArraySegment <byte> > > callback = null; callback = (x, y) => { foreach (var arraySegment in y) { received.Write(arraySegment.Array, arraySegment.Offset, arraySegment.Count); Log.Information("Received: {0} bytes, total: {1}.", arraySegment.Count, received.Length); } if (received.Length >= sent.Length) { Log.Information("Done receiving..."); done.Set(); } else { Log.Information("Receiving..."); ssl.ReceiveAsync(callback); } }; Log.Information("Receiving..."); ssl.ReceiveAsync(callback); }, "Secure");
private void InitializeSettings() { ClassType = classObjectType.world; Common.Settings.Players.OnPlayerAdded += Players_OnPlayerAdded; Common.Settings.Players.OnPlayerRemoved += Players_OnPlayerRemoved; portListener = new TcpServerListener(this); Port = 8090; Areas = new List <Area>(); Name = "Mountain"; Description = "This world has been created by the Toetag Corporate Funding Group for your life's passionate pleasures. " + "Keep your new world growing with us. \r\n" + "Invest in Toetag Corporation's Life Insurance Policies and help make our gaming addition goals a viable solution. " + "Become a gold member of our growing centers of excellence, do the right thing, " + "donate your soul to our world class gaming society's Center of Excellence. You could win big!\r\n" + "Join today. (Please sign our body donor card and be entered in our annual Grisly Corpse Competition Awards ceremony. " + "You could win a place on the top shelf of our Achievements of Horror vault that houses the very best souls of our society's " + "most fascinating players.)\r\n"; Areas.Add(Build.CreateAdminSection()); }
public TcpService(IPublisher publisher, IPEndPoint serverEndPoint, IPublisher networkSendQueue, TcpServiceType serviceType, TcpSecurityType securityType, Func <Guid, IPEndPoint, ITcpDispatcher> dispatcherFactory, TimeSpan heartbeatInterval, TimeSpan heartbeatTimeout, IAuthenticationProvider authProvider, AuthorizationGateway authorizationGateway, X509Certificate certificate, Func <X509Certificate, X509Chain, SslPolicyErrors, ValueTuple <bool, string> > sslClientCertValidator, int connectionPendingSendBytesThreshold, int connectionQueueSizeThreshold) { Ensure.NotNull(publisher, "publisher"); Ensure.NotNull(serverEndPoint, "serverEndPoint"); Ensure.NotNull(networkSendQueue, "networkSendQueue"); Ensure.NotNull(dispatcherFactory, "dispatcherFactory"); Ensure.NotNull(authProvider, "authProvider"); Ensure.NotNull(authorizationGateway, "authorizationGateway"); if (securityType == TcpSecurityType.Secure) { Ensure.NotNull(certificate, "certificate"); } _publisher = publisher; _serverEndPoint = serverEndPoint; _serverListener = new TcpServerListener(_serverEndPoint); _networkSendQueue = networkSendQueue; _serviceType = serviceType; _securityType = securityType; _dispatcherFactory = dispatcherFactory; _heartbeatInterval = heartbeatInterval; _heartbeatTimeout = heartbeatTimeout; _connectionPendingSendBytesThreshold = connectionPendingSendBytesThreshold; _connectionQueueSizeThreshold = connectionQueueSizeThreshold; _authProvider = authProvider; _authorizationGateway = authorizationGateway; _certificate = certificate; _sslClientCertValidator = sslClientCertValidator; }
public HttpServer() { try { config = ReadConfig(configFile); } catch { config = new HttpConfig("127.0.0.1", 80, "/ErrorCodes/404.html", "/ErrorCodes/405.html", "utf-8", "/root", "/FastCGINet.exe"); WriteConfig(configFile, config); } string basePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); rootFullPath = basePath + config.RootDir; connectedClients = new List <SimpleTcpClient>(); listener = new TcpServerListener(new IPEndPoint(IPAddress.Parse(config.LocalIP), config.Port)); listener.OnConnectionAccepted += Listener_OnConnectionAccepted; listener.OnException += Listener_OnException; listener.Start(); StartFastCGI(basePath + config.FastCGIPath); Console.WriteLine("Started"); }
private void StartReceive(int port) { var server = new TcpServerListener(new IPEndPoint(IPAddress.Any, port)); server.StartListening(ServerListenCallback); }
[TestCase(false, false, false, false, true)] //do not require valid client or server certificate public void should_connect_to_each_other_and_send_data_depending_on_certificate_validity_and_settings( bool useValidServerCertificate, bool useValidClientCertificate, bool validateServerCertificate, bool validateClientCertificate, bool shouldConnectSuccessfully ) { var serverEndPoint = new IPEndPoint(_ip, _port); var serverCertificate = useValidServerCertificate ? ssl_connections.GetServerCertificate() : ssl_connections.GetUntrustedCertificate(); var clientCertificate = useValidClientCertificate ? ssl_connections.GetClientCertificate() : ssl_connections.GetUntrustedCertificate(); var rootCertificates = new X509Certificate2Collection(ssl_connections.GetRootCertificate()); var sent = new byte[1000]; new Random().NextBytes(sent); var received = new MemoryStream(); var done = new ManualResetEventSlim(); var listener = new TcpServerListener(serverEndPoint); listener.StartListening((endPoint, socket) => { var ssl = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(), endPoint, socket, serverCertificate, (cert, chain, err) => validateClientCertificate ? ClusterVNode.ValidateClientCertificateWithTrustedRootCerts(cert, chain, err, rootCertificates) : (true, null), verbose: true); ssl.ConnectionClosed += (x, y) => done.Set(); if (ssl.IsClosed) { done.Set(); } Action <ITcpConnection, IEnumerable <ArraySegment <byte> > > callback = null; callback = (x, y) => { foreach (var arraySegment in y) { received.Write(arraySegment.Array, arraySegment.Offset, arraySegment.Count); Log.Information("Received: {0} bytes, total: {1}.", arraySegment.Count, received.Length); } if (received.Length >= sent.Length) { Log.Information("Done receiving..."); done.Set(); } else { Log.Information("Receiving..."); ssl.ReceiveAsync(callback); } }; Log.Information("Receiving..."); ssl.ReceiveAsync(callback); }, "Secure"); var clientSsl = TcpConnectionSsl.CreateConnectingConnection( Guid.NewGuid(), serverEndPoint.GetHost(), serverEndPoint, (cert, chain, err) => validateServerCertificate ? ClusterVNode.ValidateServerCertificateWithTrustedRootCerts(cert, chain, err, rootCertificates) : (true, null), new X509CertificateCollection { clientCertificate },
public void should_connect_to_each_other_and_send_data() { var serverEndPoint = new IPEndPoint(_ip, _port); X509Certificate cert = GetCertificate(); var sent = new byte[1000]; new Random().NextBytes(sent); var received = new MemoryStream(); var done = new ManualResetEventSlim(); var listener = new TcpServerListener(serverEndPoint); listener.StartListening((endPoint, socket) => { var ssl = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(), endPoint, socket, cert, verbose: true); ssl.ConnectionClosed += (x, y) => done.Set(); if (ssl.IsClosed) { done.Set(); } Action <ITcpConnection, IEnumerable <ArraySegment <byte> > > callback = null; callback = (x, y) => { foreach (var arraySegment in y) { received.Write(arraySegment.Array, arraySegment.Offset, arraySegment.Count); Log.Info("Received: {0} bytes, total: {1}.", arraySegment.Count, received.Length); } if (received.Length >= sent.Length) { Log.Info("Done receiving..."); done.Set(); } else { Log.Info("Receiving..."); ssl.ReceiveAsync(callback); } }; Log.Info("Receiving..."); ssl.ReceiveAsync(callback); }, "Secure"); var clientSsl = TcpConnectionSsl.CreateConnectingConnection( Guid.NewGuid(), serverEndPoint, "ES", false, new TcpClientConnector(), TcpConnectionManager.ConnectionTimeout, conn => { Log.Info("Sending bytes..."); conn.EnqueueSend(new[] { new ArraySegment <byte>(sent) }); }, (conn, err) => { Log.Error("Connecting failed: {0}.", err); done.Set(); }, verbose: true); Assert.IsTrue(done.Wait(20000), "Took too long to receive completion."); Log.Info("Stopping listener..."); listener.Stop(); Log.Info("Closing client ssl connection..."); clientSsl.Close("Normal close."); Log.Info("Checking received data..."); Assert.AreEqual(sent, received.ToArray()); }
public SocketRemotingServer(string name, IPEndPoint serverEndPoint, ISocketServerEventListener eventListener = null) { _serverListener = new TcpServerListener(serverEndPoint, eventListener, HandleRemotingRequest); _requestHandlerDict = new Dictionary <int, IRequestHandler>(); _logger = ObjectContainer.Resolve <ILoggerFactory>().Create(name ?? GetType().FullName); }
[TestCase(false, false, false, false, true)] //do not require valid client or server certificate public void should_connect_to_each_other_and_send_data_depending_on_certificate_validity_and_settings( bool useValidServerCertificate, bool useValidClientCertificate, bool validateServerCertificate, bool validateClientCertificate, bool shouldConnectSuccessfully ) { var serverEndPoint = new IPEndPoint(_ip, _port); var serverCertificate = useValidServerCertificate ? ssl_connections.GetServerCertificate() : ssl_connections.GetUntrustedCertificate(); var clientCertificate = useValidClientCertificate ? ssl_connections.GetOtherServerCertificate() : ssl_connections.GetUntrustedCertificate(); var rootCertificates = new X509Certificate2Collection(ssl_connections.GetRootCertificate()); var sent = new byte[1000]; new Random().NextBytes(sent); var received = new MemoryStream(); var done = new ManualResetEventSlim(); var listener = new TcpServerListener(serverEndPoint); listener.StartListening((endPoint, socket) => { var ssl = TcpConnectionSsl.CreateServerFromSocket(Guid.NewGuid(), endPoint, socket, () => serverCertificate, (cert, chain, err) => validateClientCertificate ? ClusterVNode <string> .ValidateClientCertificate(cert, chain, err, () => null, () => rootCertificates) : (true, null), verbose: true); ssl.ConnectionClosed += (x, y) => done.Set(); if (ssl.IsClosed) { done.Set(); } Action <ITcpConnection, IEnumerable <ArraySegment <byte> > > callback = null; callback = (x, y) => { foreach (var arraySegment in y) { received.Write(arraySegment.Array, arraySegment.Offset, arraySegment.Count); Log.Information("Received: {0} bytes, total: {1}.", arraySegment.Count, received.Length); } if (received.Length >= sent.Length) { Log.Information("Done receiving..."); done.Set(); } else { Log.Information("Receiving..."); ssl.ReceiveAsync(callback); } }; Log.Information("Receiving..."); ssl.ReceiveAsync(callback); }, "Secure"); var clientSsl = TcpConnectionSsl.CreateConnectingConnection( Guid.NewGuid(), serverEndPoint.GetHost(), serverEndPoint, (cert, chain, err) => validateServerCertificate ? ClusterVNode <string> .ValidateServerCertificate(cert, chain, err, () => null, () => rootCertificates) : (true, null), () => new X509CertificateCollection { clientCertificate }, new TcpClientConnector(), TcpConnectionManager.ConnectionTimeout, conn => { Log.Information("Sending bytes..."); conn.EnqueueSend(new[] { new ArraySegment <byte>(sent) }); }, (conn, err) => { Log.Error("Connecting failed: {0}.", err); done.Set(); }, verbose: true); Assert.IsTrue(done.Wait(20000), "Took too long to receive completion."); Log.Information("Stopping listener..."); listener.Stop(); Log.Information("Closing client TLS connection..."); clientSsl.Close("Normal close."); Log.Information("Checking received data..."); if (shouldConnectSuccessfully) { Assert.AreEqual(sent, received.ToArray()); } else { Assert.AreEqual(new byte[0], received.ToArray()); } }
//[PermissionSet(SecurityAction.Assert, Unrestricted = true)] private void InternalStart() { try { //System.Security.SecurityRules(RuleSet=System.Security.SecurityRuleSet.Level2) //using (FileStream fs = new FileStream(@"D:\Nistec\Services\Logs\qlog.log", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) //{ // StreamWriter w = new StreamWriter(fs); // create a Char writer // w.BaseStream.Seek(0, SeekOrigin.End); // set the file pointer to the end // w.Write("log test" + "\r\n"); // w.Flush(); // update underlying file //} Netlog.Debug(serviceName + " start..."); AgentManager.Start(); //m_ServerEnqueue = new PipeServerEnqueue(); //m_ServerEnqueue.Start(false); //m_ServerDequeue = new PipeServerDequeue(); //m_ServerDequeue.Start(false); //if (AgentManager.Settings.EnableQueueManager) //{ // m_ServerQueueManager = new PipeServerManager(); // m_ServerQueueManager.Start(false); //} //if (AgentManager.Settings.EnableTcpListener) //{ m_TcpServer = new TcpServerListener(); if (m_TcpServer.Adapters.Count > 0) { //m_TcpServer.Start(); } m_TcpServer.Start(); //} //if (AgentManager.Settings.EnableFolderListener) //{ // m_FolderServer = new FolderServerListener(); // m_FolderServer.Start(); //} //if (AgentManager.Settings.EnableDbListener) //{ // m_DbServer = new DbServerListener(); // m_DbServer.Start(); //} //svr.Start();//McLock.Lock.ValidateLock(), true); //host_serviceStart(); Netlog.Debug(serviceName + " started!"); } catch (Exception ex) { Netlog.Exception(serviceName + " InternalStart error ", ex, true, true); //File.AppendAllText(@"D:\Nistec\Services\MQueue.Agent\error.log", "error: " + ex.Message); } }