【.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();//开启线程
相关推荐
2401_868534784 分钟前
软考网络规划设计师SSL协议知识点详解
服务器·网络
不脱发的程序猿1 小时前
纳指ETF量化策略
数据库·人工智能·1024程序员节
程序员塔塔喵2 小时前
【MySQL篇|第一篇】索引失效的情况
数据库·mysql·索引失效
北京青蓝智慧马老师3 小时前
比外部黑客更难防的,是那个有权限的自己人(3 个脱敏复盘)
大数据·数据库·人工智能
笃行3503 小时前
拆一台数据集成产品:KFS 的骨架、肌肉和神经
数据库
4SAPI3 小时前
搭建 AI 数据分析工具大模型 API 选型指南
数据库·人工智能·架构·php·1024程序员节
额额额对了3 小时前
嵌入式 Linux 实战:i.MX6ULL 上的 CAN 通信与摄像头采集
linux·运维·服务器
灯澜忆梦4 小时前
【Linux】#10 | Linux 终端实用快捷键 + 安装应用
linux·运维·服务器
码士集团小青5 小时前
面霸篇:高频 Java 基础问题(核心卷一)
linux·服务器·数据库·redis·缓存·1024程序员节