【.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();//开启线程
相关推荐
2601_96218196几秒前
Redis Redis介绍、安装 - Redis客户端
数据库·redis·postman
.Hypocritical.38 分钟前
Tomcat本地部署+远程服务器部署超详细教程
java·服务器·tomcat
2601_962062941 小时前
Spring Boot入门——Spring Boot项目的创建
java·数据库·spring boot
段一凡-华北理工大学1 小时前
高炉炉况智能诊断与预警实战~系列文章18:预警提前量问题:过程滞后与预测窗口的权衡
服务器·网络·人工智能·机器学习·高炉智能化·炉况预警·工业预警滞后
冰暮流星1 小时前
mysql之外键约束
数据库·mysql
茶栀(*´I`*)1 小时前
数据库零基础入门指南:从基本概念到 SQL 实战
数据库·sql
ERD Online1 小时前
Cursor 连上 MCP:读一张 ER 图,提交一版建议
数据库·后端·开源·cursor·mcp
北风toto1 小时前
扩展操作码技术 · 详细笔记
运维·服务器·笔记·软件设计师
foolishlee1 小时前
openGauss postmaster退出流程
数据库
叫我:松哥2 小时前
基于flask仿小米商城管理系统,使用flask开的一个商场网站
数据库·后端·python·flask