c# TCP《四》TcpListener 多线程接收

//-----------这是服务端 TcpListener------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace ConsoleApplication15
{
    class Program
    {
        byte[] data = new byte[1024];
        public void printReceiveMsg(object Obj_tcpClient)
        {
            TcpClient tcpClient = (TcpClient)Obj_tcpClient;
            NetworkStream stream = tcpClient.GetStream();

            while (true)
            {
                if (stream.DataAvailable)
                {
                    int length = stream.Read(data, 0, data.Length);
                    string receiveMsg = Encoding.UTF8.GetString(data, 0, length);
                    Console.WriteLine("接收客户端发的数据: " + receiveMsg);
                }
            }
        }
        static void Main(string[] args)
        {
           
            TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
            listener.Start();
            Console.WriteLine("启动监听成功");

            TcpClient tcpClient = listener.AcceptTcpClient();
            NetworkStream stream = tcpClient.GetStream();

            Program p = new Program();
            Thread T = new Thread(p.printReceiveMsg);
            T.Start(tcpClient);

          
        }
    }
}

 

 

 

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页