【.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();//开启线程
相关推荐
为思念酝酿的痛4 小时前
POSIX信号量
linux·运维·服务器·后端
ccddsdsdfsdf4 小时前
DBeaver怎么链接mongoDB
数据库·mongodb
隔窗听雨眠5 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
丷丩5 小时前
Postgresql基础实践教程(十一)各种Join
数据库·postgresql·join
星夜夏空995 小时前
FreeRTOS学习(4)——内存映射
数据库·学习·mongodb
人还是要有梦想的5 小时前
linux下用搜狗输入法,中英文切换
linux·运维·服务器
9分钟带帽5 小时前
linux_通过NFS挂载远程服务器的硬盘
linux·服务器
TheRouter6 小时前
AI Agent 记忆体系建设实战:短期、长期与工作记忆的工程实现
数据库·人工智能·oracle
Omics Pro6 小时前
首个!外源天然产物综合性代谢图谱
数据库·人工智能·算法·机器学习·r语言
JAVA面经实录9177 小时前
Hibernate面试题库
数据库·oracle·hibernate