C#实现异步阻塞TCP(Send,Receive,Accept,Connect)

本文介绍了如何在C#中实现异步TCP通信,包括服务器端和客户端的操作类,详细阐述了服务器的启动、连接处理以及客户端的发送、接收流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.类

(1)服务器端操作类

    public class TcpServiceSocket
    {
        //接收数据事件
        public Action<Socket, string> recvMessageEvent = null;
        //发送结果事件
        public Action<int> sendResultEvent = null;
        //允许连接到tcp服务器的tcp客户端数量
        private int numConnections = 0;
        //连接socket
        private Socket listenSocket = null;
        //tcp服务器ip
        private string host = "";
        //tcp服务器端口
        private int port = 0;
        //控制tcp客户端连接数量的信号量
        private Semaphore maxNumberAcceptedClients = null;
        private int bufferSize = 1024;
        private List<Socket> clientSockets = null;

        public TcpServiceSocket(string host, int port, int numConnections)
        {
            if (string.IsNullOrEmpty(host))
                throw new ArgumentNullException("host cannot be null");
            if (port < 1 || port > 65535)
                throw new ArgumentOutOfRangeException("port is out of range");
            if (numConnections <= 0 || numConnections > int.MaxValue)
                throw new ArgumentOutOfRangeException("_numConnections is out of range");

            this.host = host;
            this.port = port;
            this.numConnections = numConnections;
            clientSockets = new List<Socket>();
            maxNumberAcceptedClients = new Semaphore(numConnections, numConnections);
        }

        public void Start()
        {
            try
            {
                listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                listenSocket.Bind(new IPEndPoint(IPAddress.Parse(host), port));
                listenSocket.Listen(numConnections);
                AcceptAsync();
            }
            catch (Exception)
            {
            }
        }

        private async void AcceptAsync()
        {
            await Task.Run(new Action(() =>
            {
                while (true)
                {
                    maxNumberAcceptedClients.WaitOne();

                    try
                    {
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值