【.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();//开启线程
相关推荐
倔强的石头10615 分钟前
openGauss数据库:从CentOS 7.9部署到实战验证
linux·数据库·centos
wanhengidc1 小时前
云手机是由什么组成的?
运维·服务器·web安全·游戏·智能手机
4***14902 小时前
MySQL调试技巧与工具
数据库·mysql
Arva .2 小时前
如何监控并优化慢 SQL?
数据库·sql
w***4245 小时前
【MySQL】复合查询
数据库·mysql
wanhengidc5 小时前
网站服务器都有哪些作用?
运维·服务器·科技·智能手机·云计算
卓小帅的博客5 小时前
关于实现远程服务器使用本地网络的清晰简洁的教程
服务器·网络·vscode·连接超时
q***01775 小时前
【MySQL】表的基本操作
数据库·mysql·oracle
budingxiaomoli5 小时前
存储过程和触发器
数据库
q***12536 小时前
PostgreSQL_安装部署
数据库·postgresql