【.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();//开启线程
相关推荐
码出钞能力20 分钟前
更换libc.so导致linux变砖,通过LD_PRELOAD挽救
linux·服务器
小马学嵌入式~21 分钟前
嵌入式 SQLite 数据库开发笔记
linux·c语言·数据库·笔记·sql·学习·sqlite
Java小白程序员42 分钟前
MyBatis基础到高级实践:全方位指南(中)
数据库·mybatis
Monly211 小时前
人大金仓:merge sql error, dbType null, druid-1.2.20
数据库·sql
小猪咪piggy1 小时前
【JavaEE】(24) Linux 基础使用和程序部署
linux·运维·服务器
不宕机的小马达1 小时前
【Mysql|第一篇】Mysql的安装与卸载、Navicat工具的使用
数据库·mysql
float_六七1 小时前
数据库连接池:性能优化的秘密武器
数据库·oracle·性能优化
码界奇点1 小时前
MongoDB vs MySQLNoSQL与SQL数据库的架构差异与选型指南
数据库·sql·mongodb·系统架构
IT 小阿姨(数据库)1 小时前
PgSQL中pg_stat_user_tables 和 pg_stat_user_objects参数详解
linux·运维·数据库·sql·postgresql·oracle
倔强的石头_1 小时前
Windows系统下KingbaseES数据库保姆级安装教程(附常见问题解决)
数据库