【.net core】线程的创建和方法调用

模拟线程创建socket服务端

cs 复制代码
//socket帮助类
public class SocketHelper
{
    private Socket listenerSocket;
    private IPEndPoint endPoint;

    public SocketHelper()
    {
        
        endPoint = new IPEndPoint(IPAddress.Loopback, 50020); // 端口12345
        listenerSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    }

    public void StartServer()
    {
        listenerSocket.Bind(endPoint);
        listenerSocket.Listen(10); // 最多10个连接请求排队

        Console.WriteLine("Server is running. Waiting for a connection...");

        while (true)
        {
            Socket handler = listenerSocket.Accept();
            Console.WriteLine("Connected!");

            byte[] buffer = new byte[1024];
            int bytesReceived = handler.Receive(buffer);
            string message = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
            Console.WriteLine("Received: {0}", message);

            string welcome = "Hello, and welcome to the server.";
            byte[] msg = Encoding.ASCII.GetBytes(welcome);

            handler.Send(msg);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
    }
}

创建线程及调用方法

cs 复制代码
SocketHelper socket = new SocketHelper();//创建socket帮助类实体
Thread thread = new Thread(new ThreadStart(socket.StartServer));//创建线程并制定线程执行方法
thread.Start();//开启线程
相关推荐
StarRocks_labs1 小时前
StarRocks Community Monthly Newsletter (Jun)
数据库·starrocks·数据湖·物化视图·存算分离
光电的一只菜鸡2 小时前
ubuntu之坑(十五)——设备树
linux·数据库·ubuntu
ob熔天使——武2 小时前
MySQL
数据库·mysql
小光学长3 小时前
基于vue框架的防疫物资仓库管理系统09y38(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库
saynaihe4 小时前
ubuntu 22.04 anaconda comfyui安装
linux·运维·服务器·ubuntu
小蜜蜂爱编程4 小时前
ubuntu透网方案
运维·服务器·ubuntu
时光追逐者4 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
c#·.net·.netcore
王柏龙5 小时前
aspnetcore Mvc配置选项中的ModelMetadataDetailsProviders
mvc·.netcore
头发那是一根不剩了5 小时前
nginx:SSL_CTX_use_PrivateKey failed
运维·服务器
野生技术架构师7 小时前
MySQL数据实时同步到Elasticsearch的高效解决方案
数据库·mysql·elasticsearch