【.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();//开启线程
相关推荐
ruleslol13 分钟前
MySQL的段、区、页、行 详解
数据库·mysql
while(1){yan}29 分钟前
MyBatis Generator
数据库·spring boot·java-ee·mybatis
それども39 分钟前
MySQL affectedRows 计算逻辑
数据库·mysql
是小章啊1 小时前
MySQL 之SQL 执行规则及索引详解
数据库·sql·mysql
富士康质检员张全蛋1 小时前
JDBC 连接池
数据库
yangminlei1 小时前
集成Camunda到Spring Boot项目
数据库·oracle
翼龙云_cloud1 小时前
阿里云渠道商:如何手动一键扩缩容ECS实例?
运维·服务器·阿里云·云计算
墨风如雪2 小时前
拒绝被找回!MJJ必修课:Outlook邮箱交易后的“防回手”安全设置全攻略
服务器
ChineHe2 小时前
Redis数据类型篇002_详解Strings核心命令与存储结构
数据库·redis·缓存
清水白石0083 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python