public void Init() { //RecieveService recieveService = new RecieveService() { CompleteRecieverAction = TestRecieve }; string host = "127.0.0.1"; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, 14004); ServerSocket serverSocket = new ServerSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(ipe); SendService sendService = new SendService(serverSocket); RecieveService recieveService = new RecieveService(serverSocket) { CompleteRecieverAction = TestRecieve, CompleteLogonAction = TestLogon, CompleteRecieveMessageAction = sendService.SendMessage, }; services.Add(recieveService); services.ForEach(service => { try { service.Init(); } catch (Exception e) { } }); }
private void StartServer() { ServerSocket.Bind(TcpEndPoint); ServerSocket.Listen(10); ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), ServerSocket); }
private void StartListen() { InitSocket(); try { var endPoint = new IPEndPoint(IPAddress.Parse(Ip), Port); ServerSocket.Bind(endPoint); OnReportingStatus(StatusCode.Success, $"Successfully bound to {endPoint}"); ServerSocket.Listen(1); OnReportingStatus(StatusCode.Info, $"Started iterative TCP listening on {endPoint}"); AcceptNextPendingConnection(); } catch (ObjectDisposedException) { } catch (SocketException socketException) { OnCaughtException(socketException, EventCode.Connect); } catch (SecurityException securityException) { OnCaughtException(securityException, EventCode.Connect); } catch (Exception e) { OnCaughtException(e, EventCode.Other); } }
public void Start() { Log.LogInformation("Loading queues from persistant storage"); int queueCount = 0; int messageCount = 0; foreach (var queueName in Persistence.GetQueueNames()) { var queue = Persistence.LoadQueue(queueName); Log.LogInformation($"Loading messages for {queueName}"); foreach (var message in Persistence.LoadMessages(queueName)) { queue.Enqueue(message); messageCount = 0; } Queues.Add(queue); queueCount++; } Log.LogInformation($"Loaded {queueCount} queues with a total of {messageCount} messages"); Log.LogInformation("Starting listener"); ServerSocket.Bind(EndPoint); RunThread.Start(); QueueProcessThread.Start(); }
private void SetupServer() { ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); ServerSocket.Listen(0); ServerSocket.BeginAccept(AcceptCallback, null); ServerListening?.Invoke("Server listening on port " + Port); }
public void Start(int port, int backlog) { if (!ServerSocket.Connected) { ServerSocket.Bind(new IPEndPoint(IPAddress.Any, port)); ServerSocket.Listen(backlog); ServerSocket.BeginAccept(new AsyncCallback(OnAccept), ServerSocket); } }
public SocketRemotingServer(string name, SocketSetting socketSetting, ISocketEventListener socketEventListener = null) { _serverSocket = new ServerSocket(socketEventListener); _requestHandlerDict = new Dictionary <int, IRequestHandler>(); _logger = ObjectContainer.Resolve <ILoggerFactory>() .Create(name ?? GetType() .Name); _serverSocket.Bind(socketSetting.Address, socketSetting.Port) .Listen(socketSetting.Backlog); }
public void HandleIncomingConnections() { //List<ServerThread> serverThreads = new List<ServerThread>(); Task.Run(() => { try { // Create the ServerSocket serverSocket = new ServerSocket(); var sAddr = new InetSocketAddress(Port); serverSocket.ReuseAddress = true; serverSocket.Bind(sAddr); Log.Debug(_tag, $"Server listening on {Port}."); while (!_cts.IsCancellationRequested) { // Grab the next incoming connection Socket socket = serverSocket.Accept(); Log.Debug(_tag, $"Server accepted a connection from {socket.InetAddress.CanonicalHostName}."); lock (_lock) { // Cache the socket, filed under its address connections[socket.InetAddress.CanonicalHostName] = socket; //// Create and cache a DataOutputStream for sending data over it //var dOutStream = new DataOutputStream(socket.OutputStream); // outputStreams.Add(socket, dOutStream); } // Create a new thread for this connection serverThreads[socket.InetAddress.CanonicalHostName] = new ServerThread(this, socket).Start(); //// Ack back to the connection to let it know you're hearing it (and to pass it the address you'll know it by) //ForwardTo(socket.InetAddress.CanonicalHostName, GROUPSERVER, ACK + CONNECTED_AS + socket.InetAddress.CanonicalHostName); } } catch (Exception e) { Log.Debug(_tag, $"Exception in server socket listening: \n{e}\n"); } finally { Log.Debug(_tag, $"Releasing all connections ({serverThreads.Count} of them)."); serverSocket.Close(); foreach (var sThread in serverThreads.Values) { sThread.Stop(); } } }); }
//=================================================================================================================== //=================================================================================================================== //= CALLABLE METHODS = //=================================================================================================================== //=================================================================================================================== #region -=[- CALLABLE METHODS -]=- //------------------------------------------------------------------------------------------------------------------- //- GENERAL / STARTUP - //------------------------------------------------------------------------------------------------------------------- #region -=[- GENERAL / STARTUP -]=- /// <summary> /// Initializes the TCP-Port for communication /// </summary> public void Init() { if (Debug == null || ParseMessage == null || EncodeMessage == null || LibraryExec == null) { throw new NetComException("Error: Every delegate must be set! (Debug, ParseMessage, EncodeMessage, LibraryExec)"); } Debug("Initializing...", DebugParams); ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); ServerSocket.Listen(20); Debug("Initializing Done!", DebugParams); }
public void Start() { if (IsRunning) { throw new Exception("server is already running"); } IsRunning = true; ServerSocket.Bind(IP); ServerSocket.Listen(32); OnServerStarted?.Invoke(); AcceptClient(); }
public Server() { isRunning = false; _clients = new Dictionary <string, Socket>(); ServerSocket = new ServerSocket(this); ServerSocket.Bind(8888); ServerSocket.Listen(500); ServerSocket.Accept(); if (ServerSocket._socket.Connected) { isRunning = true; } }
public static void Run() { if (System.IO.File.Exists("Config-Auth.xml") == false) { return; } TextReader configReader = File.OpenText("Config-Auth.xml"); if (configReader == null) { throw new Exception("Unable to open Config-Auth.xml"); } var doc = new XmlDocument(); var xmlReader = XmlReader.Create(configReader); doc.Load(xmlReader); var els = doc.GetElementsByTagName("AuthServer"); if (els.Count == 0) { throw new Exception("Config-Auth.xml does not contain element AuthServer"); } var el = els[0] as XmlElement; string port = el.GetAttribute("Port"); if (port == null) { throw new Exception("Config-Auth.xml does not define AuthServer port"); } string listenbacklog = el.GetAttribute("ListenBacklog"); //just some test setup for now LogonPacketHandler.Init(); MainSocket = new Networking.ServerSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); MainSocket.SetProcessor(new LogonPacketProcessor()); MainSocket.Bind(ushort.Parse(port)); MainSocket.Listen(listenbacklog == null ? 50 : int.Parse(listenbacklog)); MainSocket.Accept(); Running = true; }
public void Inproc() { using var server = new ServerSocket(); using var client = new ClientSocket(); server.Bind("inproc://client-server"); client.Connect("inproc://client-server"); client.Send("Hello"); var(routingId, clientMsg) = server.ReceiveString(); Assert.NotEqual <uint>(0, routingId); Assert.Equal("Hello", clientMsg); server.Send(routingId, "World"); var serverMsg = client.ReceiveString(); Assert.Equal("World", serverMsg); }
public static void Start(int port) { //if (ServerSocket != null && ServerSocket.Connected) //{ // ServerSocket.Disconnect(false); //} try { ServerSocket.Bind(port); ServerSocket.Listen(500); ServerSocket.Accept(); Logger.LogEvent("Start listening on " + port); } catch (Exception ex) { Logger.LogError("Error start listening on " + port + " | " + ex.Message); } IsStarted = true; }
//开启服务 private void BtnOpenServer_Click(object sender, EventArgs e) { try { if (radioBtnchooseTCP.Checked == true)//选择建立TCP { ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } if (radioBtnchooseUDP.Checked == true)//选择建立UDP { ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } IP = IPBox.Text; Port = Convert.ToInt32(PortBox.Text); //Assign the any IP of the machine and listen on port number 8080 IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(IP), Port); //Bind and listen on the given address ServerSocket.Bind(ipEndPoint); ServerSocket.Listen(8080); //Accept the incoming clients ServerSocket.BeginAccept(new AsyncCallback(OnAccept), ServerSocket); BtnOpenServer.Enabled = false; BtnCloseServer.Enabled = true; //DebugLog.Debug("socket监听服务打开"); } catch (Exception ex) { //MessageBox.Show(ex.Message, "error",MessageBoxButtons.OK, MessageBoxIcon.Error); Console.WriteLine(ex.Message + "---" + DateTime.Now.ToLongTimeString() + "出错信息:" + "\n"); //DebugLog.Debug(ex); } }
public override void StartService() { try { ServerSocket.Bind(new IPEndPoint(IPAddress.Parse(Ip), Port)); OnReportingStatus(StatusCode.Success, $"Successfully bound to {ServerSocket.LocalEndPoint}"); Receive(); } catch (ObjectDisposedException) { } catch (SocketException socketException) { OnCaughtException(socketException, EventCode.Bind); } catch (Exception e) { OnCaughtException(e, EventCode.Other); } }
public void Start(bool waitForUserTypeExit = true) { if (Started) { throw new Exception("Server already has been started."); } Stopwatch sw = new Stopwatch(); sw.Start(); Initialize(); ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port)); ServerSocket.Listen(0); ServerSocket.BeginAccept(AcceptCallback, null); Started = true; ServerStarted?.Invoke(); RunServerStartupTasks(); sw.Stop(); LogController.WriteLog(new ServerLog($"Server started in {sw.ElapsedMilliseconds}ms", "Server", "Start")); LogController.WriteLog(new ServerLog($"Running at port {Port}")); Console.WriteLine("Type 'exit' to stop; 'reboot' to send reboot request event..."); string line = ""; if (waitForUserTypeExit) { while (line != "exit") { line = Console.ReadLine(); if (line == "reboot") { RebootRequest?.Invoke(); } } } }
public void AyncTcpServer() { ServerSocket serverSocket = new ServerSocket(); serverSocket.Bind(9900); serverSocket.AddMessageHandler<SampleMessage>(SampleMessageHandler); // Get host related information. IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList; // Get endpoint for the listener. IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], 9900); long totalTime = 0; const int msgs = (int)1e5; int msgLength = 0; Action action = () => { ClientSocket clientSocket = new ClientSocket(); clientSocket.Connect(localEndPoint); Assert.IsTrue(clientSocket.Connected); Stopwatch sw = Stopwatch.StartNew(); Serializer serializer = new Serializer(); var sample = new SampleMessage { X = 38 }; var msg = serializer.Serialize(sample); msgLength = msg.Length; for (int i = 0; i < msgs; i++) { clientSocket.Send(sample); } sw.Stop(); Interlocked.Add(ref totalTime, sw.ElapsedMilliseconds); SpinWait.SpinUntil(() => counter == msgs, 2000); //networkStream.Close(); clientSocket.Close(); }; List<Action> actions = new List<Action>(); int numOfClients = 1; for (int i = 0; i < numOfClients; i++) { actions.Add(action); } Stopwatch sw2 = Stopwatch.StartNew(); Parallel.Invoke(actions.ToArray()); if (!Debugger.IsAttached) SpinWait.SpinUntil(() => counter == msgs * numOfClients, 2000); else { SpinWait.SpinUntil(() => counter == msgs * numOfClients, 60000); } sw2.Stop(); Console.WriteLine("Num Of Msgs: {0:###,###}", counter); Console.WriteLine("Average for each client {0}ms", totalTime / actions.Count); Console.WriteLine("Average Speed for each client: {0:###,###}msgs/s", (msgs / (totalTime / actions.Count)) * 1000); Console.WriteLine("Total time: {0}ms", sw2.ElapsedMilliseconds); Console.WriteLine("Msgs/s {0:###,###}", (counter / sw2.ElapsedMilliseconds) * 1000); Console.WriteLine("Msg length {0}bytes", msgLength); Assert.AreEqual(msgs * numOfClients, counter, "Not all msgs received"); }