c# Socket(服务端)异步通讯

        实现功能,记录客户端连接个数,客户端连接的地址和端口号,能够判断哪一个客户端是否断开。

        创建几个委托,可以使用Socket客户端列表,可以使用Socket和Handle记录,还可以直接记录IPEndPoint记录,或者更直接一点,使用IP地址和端口号记录客户端。

        public delegate void ReceiveBuffer(byte[] buffer);
        public delegate void ReceiveClientBuffer(byte[] buffer, string ClientID);
        public delegate void RemoveClient(string ClientID);
        public delegate void ReceiveClient(Socket socket, string ClientID);
        public delegate void HostDisconnectionEvent(string IPAddress, int Port);//主机断开连接事件

        不多说了,直接上代码,如果有不懂的,欢迎问我:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace System.Net.Securate.TCP
{
    /// <summary>
    /// TCP服务端
    /// </summary>
    public class TCPServer
    {
        private bool _IsStart = false;
        /// <summary>
        /// 获取当前服务是否启动
        /// </summary>
        public bool IsStart
        {
            get { return _IsStart; }
        }
        private TcpListener tcpServer;
        private string _Address = "0.0.0.0";
        /// <summary>
        /// 获取或设置当前的连接地址
        /// </summary>
        public string Address
        {
            get { return _Address; }
            set { _Address = value; }
        }
        private int _Port = 0;
        /// <summary>
        /// 获取或设置当前的连接端口号
        /// </summary>
        public int Port
        {
            get { return _Port; }
            set { _Port = value; }
        }
        private int _Count;
        /// <summary>
        /// 获取或设置连接的客户端个数
        /// </summary>
        public int Count
        {
            get { _Count = _TCPClients.Count; return _Count; }
            set { _Count = value; }
        }
        private List<Socket> _TCPClients = new List<Socket>();
        /// <summary>
        /// 获取连接的客户端
        /// </summary>
        public List<Socket> TCPClients
        {
            get { return _TCPClients; }
        }
        private int _ListenerCount = 2000;
        /// <summary>
        /// 获取或设置允许的最大连接数(默认为2000)
        /// </summary>
        public int ListenerCount
        {
            get { return _ListenerCount; }
            set { _ListenerCount = value; }
        }
        /// <summary>
        /// 收到数据时发生的事件
        /// </summary>
        public event ReceiveBuffer ReceiveComTemplate;
        /// <summary>
        /// 收到客户端数据时发生
        /// </summary>
        public event ReceiveClientBuffer ReceiveClientComTemplate;
        /// <summary>
        /// 接收到客户端连接事件
        /// </summary>
        public event ReceiveClient ReceiveClientComtemplate;
        /// <summary>
        /// 移除客户端事件
        /// </summary>
        public event RemoveClient RemoveClientComTemplate;
        /// <summary>
        /// 本机所有IP地址
        /// </summary>
        /// <returns></returns>
        public IPAddress[] GetIPAddress()
        {
            string hostName = Dns.GetHostName();
            IPHostEntry ipHoseEntry = Dns.GetHostEntry(hostName);
            return ipHoseEntry.AddressList;
        }
        /// <summary>
        /// 启动服务
        /// </summary>
        public void Start()
        {
            if (_Port == 0)
            {
                _IsStart = false;
                throw new Exception("请设置端口号或端口号不能为空");
            }
            IPAddress ipaddress = IPAddress.Parse(_Address);
            tcpServer = new TcpListener(ipaddress, _Port);
            tcpServer.Start(_ListenerCount);
            tcpServer.BeginAcceptSocket(new AsyncCallback(TcpAccept), tcpServer);
            _IsStart = true;
        }
        /// <summary>
        /// 接收客户端连接
        /// </summary>
        /// <param name="ia"></param>
        private void TcpAccept(IAsyncResult ia)
        {
            TcpListener server = ia.AsyncState as TcpListener;
            try
            {
                if (_IsStart)
                {
                    TcpReceive tcpreceive = new TcpReceive();
                    tcpreceive.Client = server.EndAcceptSocket(ia);
                    _TCPClients.Add(tcpreceive.Client);
                    string ClientID = tcpreceive.Client.RemoteEndPoint.ToString();
                    if (ReceiveClientComtemplate != null)
                        ReceiveClientComtemplate(tcpreceive.Client, ClientID);
                    Receive(tcpreceive);
                    server.BeginAcceptSocket(new AsyncCallback(TcpAccept), server);
                }
            }
            catch
            {
                try
                {
                    server.BeginAcceptSocket(new AsyncCallback(TcpAccept), server);
                }
                catch { }
            }
        }
        /// <summary>
        /// 收到消息
        /// </summary>
        /// <param name="tcpReceive"></param>
        private void Receive(TcpReceive tcpReceive)
        {
            tcpReceive.Client.BeginReceive(tcpReceive.Buffer, 0, tcpReceive.Buffer.Length,
                SocketFlags.None, new AsyncCallback(ReceiveCallback), tcpReceive);
        }
        /// <summary>
        /// 读取并发送消息
        /// </summary>
        /// <param name="ia"></param>
        private void ReceiveCallback(IAsyncResult ia)
        {
            if (_IsStart)
            {
                TcpReceive tcpReceive = ia.AsyncState as TcpReceive;
                if (tcpReceive != null)
                {
                    string ClientID = tcpReceive.Client.RemoteEndPoint.ToString();
                    if (!tcpReceive.Client.Connected)
                    {
                        _TCPClients.Remove(tcpReceive.Client);
                        if (RemoveClientComTemplate != null)
                            RemoveClientComTemplate.Invoke(ClientID);
                        return;
                    }
                    if (tcpReceive.Client.Poll(1000, SelectMode.SelectRead))
                    {
                        tcpReceive.Client.Shutdown(SocketShutdown.Both);
                        tcpReceive.Client.Close();
                        _TCPClients.Remove(tcpReceive.Client);
                        if (RemoveClientComTemplate != null)
                            RemoveClientComTemplate.Invoke(ClientID);
                        return;
                    }
                    if (ReceiveComTemplate != null)
                    {
                        ReceiveComTemplate.Invoke(tcpReceive.Buffer);
                    }
                    if (ReceiveClientComTemplate != null)
                        ReceiveClientComTemplate.Invoke(tcpReceive.Buffer, ClientID);
                    tcpReceive.Client.BeginReceive(tcpReceive.Buffer, 0, tcpReceive.Buffer.Length,
                        SocketFlags.None, new AsyncCallback(ReceiveCallback), tcpReceive);
                }
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="tcpClient">连接的客户端</param>
        /// <param name="buffer">发送的字节数据</param>
        public void Send(Socket tcpClient, byte[] buffer)
        {
            if (tcpClient.Connected)
            {
                tcpClient.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), tcpClient);
            }
            else
            {
                tcpClient.Shutdown(SocketShutdown.Both);
                tcpClient.Close();
                _TCPClients.Remove(tcpClient);
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="ia"></param>
        private void SendCallback(IAsyncResult ia)
        {
            Socket tcpClient = ia.AsyncState as Socket;
            tcpClient.EndSend(ia);
        }
        /// <summary>
        /// 关闭服务
        /// </summary>
        public void Close()
        {
            tcpServer.Server.Close();
            tcpServer.Stop();
            for (int i = 0; i < _TCPClients.Count; i++)
            {
                _TCPClients[i].Shutdown(SocketShutdown.Both);
                _TCPClients[i].Close();
            }
            _TCPClients.Clear();
            _IsStart = false;
        }
    }
}
 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,下面是一个简单的C# Socket服务端使用SocketAsyncEventArgs的示例代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Threading; public class SocketServer { private Socket m_serverSocket; private Semaphore m_maxAcceptedClients; private SocketAsyncEventArgsPool m_readWritePool; public SocketServer(int maxConnections) { m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 1234)); m_serverSocket.Listen(maxConnections); m_maxAcceptedClients = new Semaphore(maxConnections, maxConnections); m_readWritePool = new SocketAsyncEventArgsPool(maxConnections); for (int i = 0; i < maxConnections; i++) { SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); readEventArgs.UserToken = new AsyncUserToken(); m_readWritePool.Push(readEventArgs); } } public void Start() { StartAccept(null); } private void StartAccept(SocketAsyncEventArgs acceptEventArgs) { if (acceptEventArgs == null) { acceptEventArgs = new SocketAsyncEventArgs(); acceptEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(Accept_Completed); } else { acceptEventArgs.AcceptSocket = null; } m_maxAcceptedClients.WaitOne(); if (!m_serverSocket.AcceptAsync(acceptEventArgs)) { ProcessAccept(acceptEventArgs); } } private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop(); AsyncUserToken userToken = (AsyncUserToken)readEventArgs.UserToken; userToken.Socket = acceptEventArgs.AcceptSocket; userToken.ReadEventArgs = readEventArgs; readEventArgs.AcceptSocket = userToken.Socket; if (!userToken.Socket.ReceiveAsync(readEventArgs)) { ProcessReceive(readEventArgs); } StartAccept(acceptEventArgs); } private void Accept_Completed(object sender, SocketAsyncEventArgs e) { ProcessAccept(e); } private void IO_Completed(object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Receive: ProcessReceive(e); break; case SocketAsyncOperation.Send: ProcessSend(e); break; default: throw new ArgumentException("The last operation completed on the socket was not a receive or send"); } } private void ProcessReceive(SocketAsyncEventArgs e) { AsyncUserToken userToken = (AsyncUserToken)e.UserToken; if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) { userToken.Data.AddRange(e.Buffer.Take(e.BytesTransferred)); if (userToken.Data.Count >= 4) { int len = BitConverter.ToInt32(userToken.Data.Take(4).ToArray(), 0); if (userToken.Data.Count >= 4 + len) { byte[] buffer = userToken.Data.Skip(4).Take(len).ToArray(); userToken.Data.RemoveRange(0, 4 + len); // 处理请求并响应 byte[] response = HandleRequest(buffer); Send(userToken.Socket, response); return; } } if (!userToken.Socket.ReceiveAsync(e)) { ProcessReceive(e); } } else { CloseClientSocket(userToken); } } private void ProcessSend(SocketAsyncEventArgs e) { AsyncUserToken userToken = (AsyncUserToken)e.UserToken; if (e.SocketError == SocketError.Success) { if (!userToken.Socket.ReceiveAsync(userToken.ReadEventArgs)) { ProcessReceive(userToken.ReadEventArgs); } } else { CloseClientSocket(userToken); } } private void Send(Socket socket, byte[] buffer) { SocketAsyncEventArgs sendEventArgs = new SocketAsyncEventArgs(); sendEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed); sendEventArgs.SetBuffer(buffer, 0, buffer.Length); sendEventArgs.UserToken = socket; if (!socket.SendAsync(sendEventArgs)) { ProcessSend(sendEventArgs); } } private void CloseClientSocket(AsyncUserToken userToken) { try { userToken.Socket.Shutdown(SocketShutdown.Send); } catch (Exception) { } userToken.Socket.Close(); m_readWritePool.Push(userToken.ReadEventArgs); m_maxAcceptedClients.Release(); } private byte[] HandleRequest(byte[] request) { // 处理请求并响应 return null; } } public class AsyncUserToken { public Socket Socket { get; set; } public List<byte> Data { get; set; } public SocketAsyncEventArgs ReadEventArgs { get; set; } public AsyncUserToken() { Data = new List<byte>(); } } ``` 以上示例代码演示了如何使用SocketAsyncEventArgs实现一个简单的Socket服务端,其中包含了异步接收、异步发送和连接池等功能。当有客户端连接时,它会从连接池中获取一个SocketAsyncEventArgs对象,并使用它来进行通信。在通信完成后,它会将SocketAsyncEventArgs对象放回连接池中,以便于重用。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值