【.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();//开启线程
相关推荐
CodeMartain2 小时前
Redis为什么快?
数据库·redis·缓存
Anastasiozzzz4 小时前
深入研究RAG: 在线阶段-查询&问答
数据库·人工智能·ai·embedding
Boop_wu7 小时前
[Java 算法] 字符串
linux·运维·服务器·数据结构·算法·leetcode
卤炖阑尾炎8 小时前
基于 MySQL 主主复制 + HAProxy+Keepalived 构建高可用集群实战
数据库·mysql
Dxy12393102168 小时前
MySQL 如何高效删除大量数据:策略与最佳实践
数据库·mysql·oracle
m0_694845578 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
倔强的石头_8 小时前
从 “不得不存” 到 “战略必争”:工业数据的价值觉醒之路
数据库
码云数智-大飞9 小时前
C++ RAII机制:资源管理的“自动化”哲学
java·服务器·php
倔强的石头_9 小时前
新型电力系统应该用什么数据库?——时序数据库选型与落地实战
数据库
SkyXZ~9 小时前
Jetson有Jtop,Linux有Htop,RDK也有Dtop!
linux·运维·服务器·rdkx5·rdks100·dtop