【.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();//开启线程
相关推荐
apcipot_rain1 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python
辛一一3 小时前
neo4j图数据库基本概念和向量使用
数据库·neo4j
Vone_664 小时前
node.js 邮箱验证服务器搭建
运维·服务器·node.js
巨龙之路4 小时前
什么是时序数据库?
数据库·时序数据库
蔡蓝4 小时前
binlog日志以及MySQL的数据同步
数据库·mysql
丢丢丢丢丢丢~5 小时前
apache2的默认html修改
linux·运维·服务器
wusam5 小时前
Linux系统管理与编程20:Apache
linux·运维·服务器·apache·shell编程
ChironW5 小时前
Ubuntu 24.04 LTS系统上配置国内时间同步
linux·运维·服务器·ubuntu
TPBoreas5 小时前
排查服务器内存空间预警思路
运维·服务器
是店小二呀5 小时前
【金仓数据库征文】金融行业中的国产化数据库替代应用实践
数据库·金融·数据库平替用金仓·金仓数据库2025征文