【.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();//开启线程
相关推荐
l12586524 分钟前
# RAG上线评估指标体系:六大核心指标与压测实战全解析
数据库·人工智能·python·mysql·langchain·milvus
一只鹿鹿鹿1 小时前
数据资产管理解决方案(Word文件)
大数据·数据库·安全·web安全·系统安全
2401_894915531 小时前
Geo 优化源码部署实战:环境配置、参数调优完整指南
运维·服务器·数据库·tcp/ip·安全
FfHUCisI1 小时前
Golang database/sql 标准库基础
数据库·sql·golang
zhanghaha13141 小时前
Python进阶教程:13_math 模块 —— 新手完全指南
数据库·python·机器学习
__zRainy__2 小时前
Node系列 · 数据库:单表查询
数据库·后端·mysql·node.js
xcLeigh2 小时前
聊聊数据库迁移工具怎么从单机走向“云+端+服务”,KDMS架构拆解
数据库·架构·数据库迁移·kes·kdms·架构拆解
St_rive2 小时前
selenium cookie的处理
数据库·selenium·测试工具
辻弋2013 小时前
一键优化电源计划、游戏模式、独显强制、禁用后台录制——DeltaForceBooster专治三角洲行动卡顿掉帧,所有改动可一键还原
服务器·数据库·windows·游戏·电脑·php
xcLeigh3 小时前
Go入门:基本数据类型全览与选择指南
android·服务器·golang·教程·go热门