【.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();//开启线程
相关推荐
阿拉斯攀登14 小时前
向量数据库选型:Milvus vs Chroma vs Elasticsearch
数据库·elasticsearch·milvus·知识库·rag·个人知识库
彦为君14 小时前
Redis最新版本特性
java·数据库·redis·算法·bootstrap
vigor51215 小时前
MySQL通过Mango实现分库分表
android·数据库·mysql
weixin1997010801615 小时前
[特殊字符]《京东订单API(jd.order.detail.get)对接ERP:企业认证+OAuth授权避坑指南》(附Python源码)
java·数据库·python
赵渝强老师15 小时前
【赵渝强老师】高斯数据库(openGauss)的模式
数据库·opengauss·国产数据库·高斯数据库
长不胖的路人甲15 小时前
Redis 数据删除策略
数据库·redis·spring
ClouGence15 小时前
SQL Server CDC 如何降低主库压力?Always On 备库读取实践
数据库·后端·sql·sqlserver
researcher-Jiang15 小时前
高性能计算之MPI:第一次MPI并行程序设计练习
linux·运维·服务器
尽兴-16 小时前
Redis 为什么快?
数据库·redis·内存
林澈在路上16 小时前
最新版权清晰 AI音乐写歌工具软件App推荐 商用全场景实测指南
数据库·人工智能·ai·aigc·音频