【.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();//开启线程
相关推荐
神龙斗士24011 小时前
增删改查操作
数据库·mysql
Elastic 中国社区官方博客11 小时前
13.7万人,零人工决策:使用 Elasticsearch 实现智能体驱动的灾害响应系统
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
yuzhiboyouye11 小时前
sql增删改查怎么写?有时会不会有联表查询的增删查改
数据库·sql
jingyu飞鸟12 小时前
openEuler 22.03 LTS SP4安装华为opengauss 22.03 LTS版本数据库,一键复制安装使用,保姆级教程
数据库·华为
bloglin9999912 小时前
TabClaw(交互式表格分析 AI 智能体)在线下载,离线部署
linux·运维·服务器·tabclaw
IvorySQL12 小时前
【HOW 2026 分论坛演讲】PG/IvorySQL私有云中实践
数据库·人工智能·sql·postgresql
云栖梦泽12 小时前
WIFI通信测试
linux·运维·服务器·压力测试
SAP庖丁解码12 小时前
【采购申请的校验——成本中心范围】
数据库
wefg112 小时前
【Linux】网络高级 IO
linux·运维·服务器