码迷,mamicode.com
首页 > 其他好文 > 详细

测试TestTcp

时间:2020-12-22 12:32:26      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:encoding   connect   oid   socket   sync   write   ima   col   pad   

测试TestTcp请求----处理Socket,代码如下:

#region 测试TestTcp

        /// <summary>
        /// 测试TestTcp
        /// </summary>
        public static async void TestTcp()
        {
            var threadStart = new Thread(new ThreadStart(StartTestTcp))
            {
                IsBackground = true
            };
            threadStart.Start();
            Console.WriteLine($"TestTcp开始测试数据");

            int test = 1;
            while (true)
            {
                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(IPAddress.Parse("127.0.0.1"), 1122);
                Console.WriteLine($"TcpClient 发送数据:{test}");
                await tcpClient.GetStream().WriteAsync(Encoding.UTF8.GetBytes($"client{test}"));

                var buffer = new byte[1024];
                var socketConnReceCount = await tcpClient.GetStream().ReadAsync(buffer, 0, buffer.Length);
                Console.WriteLine($"TcpClient 接收数据:{Encoding.UTF8.GetString(buffer, 0, socketConnReceCount)}");

                test++;
                Thread.Sleep(2000);
                tcpClient.Dispose();
            }
        }

        public static async void StartTestTcp()
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1122);
            tcpListener.Start();
            int test = 1;
            Console.WriteLine($"TcpListener服务端 启动监听");
            while (true)
            {
                var tcpclient = await tcpListener.AcceptTcpClientAsync();
                var bytes = new byte[1024];
                var readdataCount = await tcpclient.GetStream().ReadAsync(bytes, 0, bytes.Length);
                Console.WriteLine($"TcpListener服务端接收数据:{Encoding.UTF8.GetString(bytes, 0, readdataCount)}");

                bytes = Encoding.UTF8.GetBytes($"服务端已处理{test}");
                await tcpclient.GetStream().WriteAsync(bytes, 0, bytes.Length);
                tcpclient.Dispose();
            }
        }

        #endregion

 

测试结果如下:

 public class Program
    {
        static void Main(string[] args)
        {
             #region 测试TestTcp
            TestTcp();
            #endregion
            Console.Read();
        }
    }

技术图片

 

测试TestTcp

标签:encoding   connect   oid   socket   sync   write   ima   col   pad   

原文地址:https://www.cnblogs.com/1175429393wljblog/p/14150425.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!