/// <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; }
public static void StartServer() { server = new AsyncTcpListener { IPAddress = IPAddress.IPv6Any, Port = 2222, ClientConnectedCallback = tcpClient => new AsyncTcpClient { ServerTcpClient = tcpClient, ConnectedCallback = async(serverClient, isReconnected) => { await Task.Delay(500); byte[] bytes = Encoding.UTF8.GetBytes($"Hello, {tcpClient.Client.RemoteEndPoint}, 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); Log.Debug("Server client: received: {0}", message); if (message.Contains("REQ")) { bytes = Encoding.UTF8.GetBytes("Server=>Webcam.GetFrame()"); } else { bytes = Encoding.UTF8.GetBytes("No frame requested=>" + message); } await serverClient.Send(new ArraySegment <byte>(bytes, 0, bytes.Length)); if (message == "bye") { // Let the server close the connection serverClient.Disconnect(); } } }.RunAsync() }; server.Message += (s, a) => Log.Debug("Server: {0}", a.Message); server.RunAsync().GetAwaiter().GetResult(); }
/// <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; }
/// <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; }