C# Socket(TCP)服务端

public class ServerSocket
    {
        private string _ip = string.Empty;
        //创建的事件用于传递数据到UI上
        Infomation _infomation = null;
        //端口号
        private int _port = 0;
        //服务端通道
        private Socket _socket = null;
        private byte[] _buffer = null;
        Task _task;
        //通道字典
        Dictionary<string, Socket> _socketDictory = new Dictionary<string,Socket>();
        //Task Token字典
        Dictionary<string, CancellationTokenSource> tokenSourcekeyValuePairs = new Dictionary<string, CancellationTokenSource>();

        //
        public ServerSocket(string ip,int port,Infomation infomation)
        {
           _port= port;
            _ip = ip;
            _infomation = infomation;
        }
        public ServerSocket(int port, Infomation infomation)
        {
            _port= port;
            _infomation = infomation;
            _ip = IPAddress.Any.ToString();
        }

        //创建套子设置连接数,开始监听
        public void StartListen() 
        {
            try
            {
                //1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)
                _socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                //2.0 创建IP对象
                IPAddress iPAddress = IPAddress.Parse(_ip);
                //3.0 创建网络端口,包括ip和端口
                IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, _port);
                //4.0 绑定套接字
                _socket.Bind(iPEndPoint);
                //5.0 设置最大连接数
                _socket.Listen(int.MaxValue);
                _infomation.Invoke($"监听{_socket.LocalEndPoint.ToString()}消息成功");
                //6.0 开始监听
                Task.Run(() => ListenClientConnect());
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        //监听客户端的连接请求
        private void ListenClientConnect() 
        {
            try
            {
                while (true)
                {
                    Socket clientSocket = _socket.Accept();
                    if (clientSocket != null) 
                    {
                        _socketDictory.Add(clientSocket.RemoteEndPoint.ToString(), clientSocket);
                        CancellationTokenSource tokenSource = new CancellationTokenSource();
                        tokenSourcekeyValuePairs.Add(clientSocket.RemoteEndPoint.ToString(), tokenSource);
                        clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));
                        Task.Factory.StartNew(() => ReceiveMessage(clientSocket), tokenSource.Token);
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        //发送信息
        public void SendMessage(string msg)
        {
            if (_socketDictory.Count != 0)
            {
                Socket socket = _socketDictory.First().Value;
                socket.Send(Encoding.UTF8.GetBytes(msg));
                _infomation.Invoke($"{socket.LocalEndPoint} To {socket.RemoteEndPoint}: {msg}");
            }
            else
            {
                _infomation.Invoke($"没有连接到任何用户");
            }
        }

        //关闭连接
        public void close() 
        {
            foreach (var item in tokenSourcekeyValuePairs)
            {
                item.Value.Cancel();
            }
            tokenSourcekeyValuePairs.Clear();
            foreach (var item in _socketDictory)
            {
                item.Value.Close();
            }
            _socketDictory.Clear();
        }

        //接收信息
        private void ReceiveMessage(object socket) 
        {
            Socket clientSocket = (Socket)socket;
            byte[] buffer = new byte[1024];
            while (true)
            {
                try
                {
                    int length = clientSocket.Receive(buffer);
                    if (length > 0) 
                    { 
                        _infomation.Invoke($"接收客户端{clientSocket.RemoteEndPoint.ToString()},消息{Encoding.UTF8.GetString(buffer, 0, length)}"); 
                    }
                }
                catch (Exception ex)
                {
                    _infomation.Invoke(ex.Message);
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                    break;
                }
            }
        }

    }
此条目发表在C#, Socket分类目录。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注