/// <summary> /// Demonstrates the client and server with derived classes. /// </summary> /// <returns></returns> private async Task RunAsync() { int port = 7777; var server = new AsyncTcpListener <DemoTcpServerClient> { IPAddress = IPAddress.IPv6Any, Port = port }; server.Message += (s, a) => Console.WriteLine("Server: " + a.Message); var serverTask = server.RunAsync(); var client = new DemoTcpClient { IPAddress = IPAddress.IPv6Loopback, Port = port, //AutoReconnect = true }; client.Message += (s, a) => Console.WriteLine("Client: " + a.Message); var clientTask = client.RunAsync(); await Task.Delay(10000); Console.WriteLine("Program: stopping server"); server.Stop(true); await serverTask; client.Dispose(); await clientTask; }
/// <summary> /// Stop it /// </summary> public void Stop() { if (IsListening) { IsListening = false; m_listener.Stop(); } }
public void Stop() { //Server.Close(); if (!IsListening) { return; } IsListening = false; infoTimer.Stop(); this.OnServerStop(); lock (DuelServers) { foreach (DuelServer server in DuelServers) { server.Close(); } } lock (Clients) { foreach (Session client in Clients.Values) { client.Close(); } } lock (Porcess) { foreach (ServerProcess p in Porcess) { p.Close(); } } if (m_apilistener != null) { m_apilistener.Stop(); } if (m_listener != null) { m_listener.Stop(); } }
/// <summary> /// Demonstrates the client and server by using the classes directly with callback methods. /// </summary> /// <returns></returns> private async Task RunAsync2() { int port = 7777; var server = new AsyncTcpListener { IPAddress = IPAddress.IPv6Any, Port = port, ClientConnectedCallback = tcpClient => new AsyncTcpClient { ServerTcpClient = tcpClient, ConnectedCallback = async(serverClient, isReconnected) => { await Task.Delay(500); byte[] bytes = Encoding.UTF8.GetBytes("Hello, my name is Server. Talk to me."); await serverClient.Send(new ArraySegment <byte>(bytes, 0, bytes.Length)); }, ReceivedCallback = async(serverClient, count) => { byte[] bytes = serverClient.ByteBuffer.Dequeue(count); string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length); Console.WriteLine("Server client: received: " + message); bytes = Encoding.UTF8.GetBytes("You said: " + message); await serverClient.Send(new ArraySegment <byte>(bytes, 0, bytes.Length)); } }.RunAsync() }; server.Message += (s, a) => Console.WriteLine("Server: " + a.Message); var serverTask = server.RunAsync(); var client = new AsyncTcpClient { IPAddress = IPAddress.IPv6Loopback, Port = port, //AutoReconnect = true, ConnectedCallback = async(c, isReconnected) => { await c.WaitAsync(); // Wait for server banner await Task.Delay(50); // Let the banner land in the console window Console.WriteLine("Client: type a message at the prompt, or empty to quit (server shutdown in 10s)"); while (true) { Console.Write("> "); var consoleReadCts = new CancellationTokenSource(); var consoleReadTask = ConsoleEx.ReadLineAsync(consoleReadCts.Token); // Wait for user input or closed connection var completedTask = await Task.WhenAny(consoleReadTask, c.ClosedTask); if (completedTask == c.ClosedTask) { // Closed connection consoleReadCts.Cancel(); break; } // User input string enteredMessage = await consoleReadTask; if (enteredMessage == "") { c.Dispose(); break; } byte[] bytes = Encoding.UTF8.GetBytes(enteredMessage); await c.Send(new ArraySegment <byte>(bytes, 0, bytes.Length)); // Wait for server response or closed connection await c.ByteBuffer.WaitAsync(); if (c.IsClosing) { break; } } }, ReceivedCallback = (c, count) => { byte[] bytes = c.ByteBuffer.Dequeue(count); string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length); Console.WriteLine("Client: received: " + message); return(Task.CompletedTask); } }; client.Message += (s, a) => Console.WriteLine("Client: " + a.Message); var clientTask = client.RunAsync(); await Task.Delay(10000); Console.WriteLine("Program: stopping server"); server.Stop(true); await serverTask; client.Dispose(); await clientTask; }
private static void Main() { Thread.CurrentThread.Name = nameof(ExampleServer); var headerArea = new DisplayArea(HEADER_AREA, 0, 0, HEADER_LINES - 1, Console.WindowWidth); var totalConnectionArea = new DisplayArea(STATS_TOTAL_CONNECTION_AREA, headerArea.Bottom + 1, 0, headerArea.Bottom + 1, Console.WindowWidth) { Cycle = true }; var activeConnectionArea = new DisplayArea(STATS_ACTIVE_CONNECTION_AREA, totalConnectionArea.Bottom + 1, 0, totalConnectionArea.Bottom + 1, Console.WindowWidth) { Cycle = true }; var logAreaDemarcation = new DisplayArea(LOG_AREA_DEMARCATION, activeConnectionArea.Bottom + 1, 0, activeConnectionArea.Bottom + 1, Console.WindowWidth) { Cycle = true }; var logArea = new DisplayArea(LOG_AREA, logAreaDemarcation.Bottom + 1, 0, Console.WindowHeight - logAreaDemarcation.Bottom, Console.WindowWidth) { Cycle = true }; _consoleWindow = new ConsoleWindow(new[] { headerArea, totalConnectionArea, activeConnectionArea, logAreaDemarcation, logArea }); _consoleWindow.Clear(); _consoleWindow.WriteLine($"Locating hosting information...", Flair.Log, HEADER_AREA); _consoleWindow.WriteLine($"-----------------------LOG-------------------------", Flair.Log, LOG_AREA_DEMARCATION); var service = new AsyncTcpListener("Listener Simulator", 20000); Task.Run(() => { service.DebugMessageEventHandler += (sender, e) => { _consoleWindow.WriteLine($"{e.Timestamp.TimeOfDay} - {e.SourceName} - {e.Message}", Flair.Log, LOG_AREA); }; service.InfoMessageEventHandler += (sender, e) => { _consoleWindow.WriteLine($"{e.Timestamp.TimeOfDay} - {e.SourceName} - {e.Message}", Flair.Log, LOG_AREA); }; service.ConnectionInfoMessageEventHandler += (sender, e) => { _consoleWindow.WriteLine($"{e.Timestamp.TimeOfDay} - Client Connections {e.Stats.ClientConnectionsCount}", Flair.Log, STATS_TOTAL_CONNECTION_AREA); _consoleWindow.WriteLine($"{e.Timestamp.TimeOfDay} - Active Connections {e.Stats.ActiveClientCount}", Flair.Log, STATS_ACTIVE_CONNECTION_AREA); }; service.ErrorMessageEventHandler += (sender, e) => { _consoleWindow.WriteLine($"{e.Timestamp.TimeOfDay} - {e.SourceName} - {e.Message} - {e.Exception}", Flair.Error, LOG_AREA); }; service.ResponseEventHandler += (sender, eventArgs) => { if (eventArgs == null) { throw new ArgumentNullException(nameof(eventArgs)); } _consoleWindow.WriteLine($"Got {eventArgs.RequestMessage}", Flair.Log, LOG_AREA); if (string.IsNullOrWhiteSpace(eventArgs.RequestMessage)) { eventArgs.ResponseMessage = "¿Huh?"; } else if (eventArgs.RequestMessage.StartsWith(TRIGGER_TEXT, StringComparison.OrdinalIgnoreCase)) { eventArgs.ResponseMessage = $"REPLYING FROM Serverside for {eventArgs.RequestMessage.Replace(TRIGGER_TEXT, string.Empty)}"; } else { eventArgs.ResponseMessage = "W/E"; } }; service.Run(); return(Task.CompletedTask); }); _consoleWindow.WriteLine("Press ESC to stop listening", Flair.Success, HEADER_AREA); _consoleWindow.WaitForKey(ConsoleKey.Escape); service.Stop(); _consoleWindow.Close(); }
/// <summary> /// 数据中心服务 /// </summary> /// <returns></returns> private async Task StartTask() { IOConfig = new CenterServerConfig(); //////////监听端处理 int port = 8888;//默认是8888端口 int.TryParse(IOConfig.LocalPort, out port); var server = new AsyncTcpListener { //获取本机IP地址 IPAddress = IPAddress.Parse(GetLocalIp()), Port = port, ClientConnectedCallback = tcpClient => new AsyncTcpClient { //获取或设置要使用的TcpClient。仅适用于接收 ServerTcpClient = tcpClient, //连接服务器成功 ConnectedCallback = async(serverClient, isReconnected) => { await Task.Delay(100); if (MessageEvent != null) { MessageEvent(serverClient.IPAddress.ToString() + "连接成功: ", null); } //服务器连接成功 }, //接收客户端数据,并处理 ReceivedCallback = async(serverClient, count) => { byte[] bytes = serverClient.ByteBuffer.Dequeue(count); string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (MessageEvent != null) { MessageEvent(serverClient.IPAddress.ToString() + "SendData: " + message, null); } string[] infos = message.Split('-'); switch (infos[0]) { case "SELECT": //查询sql语句 break; case "UPDATE": //更新sql语句 break; case "INSERT": //插入sql语句 break; case "DELETE": //删除sql语句 break; case "PUBLISH": //采集站发布 break; } //发送数据或者执行操作 bytes = Encoding.UTF8.GetBytes("You said: " + message); await serverClient.Send(new ArraySegment <byte>(bytes, 0, bytes.Length)); //断开连接,防止长时间被占用 serverClient.Disconnect(); } }.RunAsync() }; server.Message += (s, a) => { if (MessageEvent != null) { MessageEvent("Server: " + a.Message, null); } }; var serverTask = server.RunAsync(); server.Stop(true); await serverTask; }