【.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();//开启线程
相关推荐
✿ ༺ ོIT技术༻2 分钟前
MySQL:MySQL库和表的基本操作
数据库·mysql
奔波霸的伶俐虫23 分钟前
liunx磁盘挂载和jar启动命令
linux·运维·服务器
安於宿命30 分钟前
【MySQL】库和表的操作
数据库·mysql·oracle
椰椰椰耶1 小时前
【redis】应用场景:缓存功能和计数功能
数据库·redis·缓存
椛椛~1 小时前
MySQL数据库操作
数据库·mysql·oracle
一直在学习的小白~3 小时前
Nginx 服务器,Apache 服务器,IIS 服务器的区别
服务器·nginx·apache
羑悻的小杀马特3 小时前
蓝耘携手通义万象 2.1 图生视频:开启创意无限的共享新时代
服务器·nginx·音视频·ai大模型·蓝耘·通义万象 2.1
若云止水4 小时前
Ubuntu 下 nginx-1.24.0 源码分析 - ngx_core_module
数据库·nginx·ubuntu
WZF-Sang5 小时前
Linux——基础IO【3万字大章】
linux·服务器·c++·学习·文件系统·软硬链接·动态库静态库