C# TCP异步通信TcpClient

服务端监听

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleAppTcp
{
    class Program
    {
        private static readonly object _object = new object();
        static void Main(string[] args)
        {
            TcpListener listener = null;
            try
            {
                listener = new TcpListener(System.Net.IPAddress.Parse("127.0.0.1"), 9866);
                listener.Start();
                Console.WriteLine("启动监听");
                Task.Run(() =>
                {
                    while (true)
                    {
                        lock (_object)
                        {
                            listener.BeginAcceptTcpClient(new AsyncCallback((a) =>
                            {
                                TcpListener tcpListener = (TcpListener)a.AsyncState;
                                TcpClient client = tcpListener.EndAcceptTcpClient(a);
                                string ip = client.Client.RemoteEndPoint.ToString();
                                Console.WriteLine("收到客户端连接" + ip);

                                Task task = Task.Run(async () =>
                                {
                                    NetworkStream stream = client.GetStream();              
                                    while (true)
                                    {
                                        try
                                        {
                                            if (!stream.CanRead)
                                            {
                                                continue;
                                            }
                                            //收到客户端消息
                                            List<byte> list=new List<byte>();
                                            do
                                            {
                                                Memory<byte> buffer3 = new byte[200];
                                                await stream.ReadAsync(buffer3);
                                                list.AddRange(buffer3.ToArray());
                                            } while (stream.DataAvailable);
                                            string msg = Encoding.Unicode.GetString(list.ToArray());
                                            msg = msg.TrimEnd('\0','\r','\n');
                                            Console.WriteLine("收到客户端"+ ip + "消息:" + msg);
                                             
                                            //发送消息到客户端
                                            string input = "王安石变法" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                                            Console.WriteLine("发送到" + ip + "客户端>" + input);
                                            ReadOnlyMemory<byte> buffer2 = Encoding.Unicode.GetBytes(input).AsMemory();
                                            await stream.WriteAsync(buffer2);
                                            await stream.FlushAsync();
                                        }
                                        catch (Exception ex)
                                        {
                                            Console.WriteLine("读取客户端消息异常." + ex.Message);
                                            break;
                                        }
                                        //Thread.Sleep(50);
                                    }
                                });
                            }), listener);
                        }
                        Thread.Sleep(100);
                    }
                });
            }
            catch (SocketException ex)
            {
                Console.WriteLine("监听异常" + ex);
            }
            finally
            {
                //listener?.Stop();
            }
            Console.ReadLine();


        }
    }
}


客户端代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleAppTcpClient
{
    /// <summary>
    /// 客户端代码
    /// </summary>
    class Program
    {

        private static readonly object obj = new object();

        /// <summary>
        /// 是否继续连接了
        /// </summary>
        static bool isContinueConnect = false;

        static void Main(string[] args)
        {
            Action action = null;

            //继续连接服务器
            Action continueConnect = () => {
                lock (obj) {
                    if (!isContinueConnect)
                    {
                        isContinueConnect = true;
                        action();
                    }                  
                }
            };

            action = () =>
          {
              TcpClient tcpClient = new TcpClient();
              tcpClient.BeginConnect(IPAddress.Parse("127.0.0.1"), 9866, a =>
               {
                   TcpClient tcpClient = null;
                   try
                   {
                       tcpClient = (TcpClient)a.AsyncState;
                       tcpClient.EndConnect(a);
                       Console.WriteLine("连接服务器成功");
                       isContinueConnect = false;

                       NetworkStream networkStream = tcpClient.GetStream();
                       Task t1 = Task.Run(async () =>
                       {
                           while (true)
                           {
                               try
                               {
                                   if (!networkStream.CanWrite)
                                   {
                                       continue;
                                   }
                                   //发送消息到服务器
                                   string input = "武松去九岭岗" + DateTime.Now.ToLongTimeString();
                                   Console.WriteLine("发送到服务器:" + input);
                                   ReadOnlyMemory<byte> buffer = Encoding.Unicode.GetBytes(input).AsMemory();
                                   await networkStream.WriteAsync(buffer);
                                   await networkStream.FlushAsync();

                                   Thread.Sleep(2000);
                               }
                               catch (Exception ex)
                               {
                                   Console.WriteLine("连接服务器异常" + ex.Message);
                                   continueConnect();
                                   break;
                               }
                           }                         
                       });
                       Task t2 = Task.Run(async () =>
                       {
                           while (true)
                           {
                               try
                               {
                                   if (!networkStream.CanRead)
                                   {
                                       continue;
                                   }
                                   //收到服务器消息
                                   List<byte> list = new List<byte>();
                                   do
                                   {
                                       Memory<byte> buffer3 = new byte[200];
                                       await networkStream.ReadAsync(buffer3);
                                       list.AddRange(buffer3.ToArray());
                                   } while (networkStream.DataAvailable);
                                   string msg = Encoding.Unicode.GetString(list.ToArray());
                                   msg = msg.TrimEnd('\0', '\r', '\n');
                                   Console.WriteLine("收到服务器消息:" + msg);
                               }
                               catch (Exception ex)
                               {
                                   Console.WriteLine("连接服务器异常" + ex.Message);
                                   continueConnect();
                                   break;
                               }
                           }                            
                       });                               
                   }
                   catch (Exception ex)
                   {
                       Console.WriteLine(ex.Message + ",10秒后重新连接");
                       Thread.Sleep(10000);
                       action();
                   }
               }, tcpClient);
          };          
            action();
            Console.ReadKey();
        }

    

    }
}


在这里插入图片描述

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用C#中的异步编程模型来创建一个通信服务器端。下面是一个示例代码,演示了如何使用AsyncTcpServer类来实现: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; class AsyncTcpServer { private TcpListener listener; public AsyncTcpServer(IPAddress ipAddress, int port) { listener = new TcpListener(ipAddress, port); } public async Task Start() { listener.Start(); Console.WriteLine("Server started. Listening for incoming connections..."); while (true) { TcpClient client = await listener.AcceptTcpClientAsync(); HandleClient(client); } } private async void HandleClient(TcpClient client) { Console.WriteLine($"Client connected: {client.Client.RemoteEndPoint}"); try { NetworkStream stream = client.GetStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { string requestData = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"Received data from client: {requestData}"); // 处理接收到的数据并返回响应 string responseData = $"Server received: {requestData}"; byte[] responseBytes = Encoding.ASCII.GetBytes(responseData); await stream.WriteAsync(responseBytes, 0, responseBytes.Length); Console.WriteLine($"Sent response to client: {responseData}"); } } catch (Exception ex) { Console.WriteLine($"Error occurred: {ex.Message}"); } finally { client.Close(); Console.WriteLine($"Client disconnected: {client.Client.RemoteEndPoint}"); } } } class Program { static async Task Main(string[] args) { IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); int port = 8080; AsyncTcpServer server = new AsyncTcpServer(ipAddress, port); await server.Start(); } } ``` 你可以根据需要修改IP地址和端口号。这个示例创建了一个异步的TCP服务器,接受客户端连接并处理接收到的数据。它使用ASCII编码来传输文本数据,你可以根据需要进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王焜棟琦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值