C# 多个 socket 当做变量保存

发布于:2024-08-03 ⋅ 阅读:(86) ⋅ 点赞:(0)

在C#中,可以使用字典(Dictionary)来保存多个Socket对象,其中键(Key)可以是一个标识符,而值(Value)就是Socket对象。以下是一个简单的例子:

using System;
using System.Collections.Generic;
using System.Net.Sockets;
 
public class SocketManager
{
        public static Dictionary<string, Socket> _sockets = new Dictionary<string, Socket>();//key是Socket的名称,value是Socket
        /// <summary>
        /// 添加Socket
        /// </summary>
        /// <param name="id">Key</param>
        /// <param name="socket">Value</param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddSocket(string id, Socket socket)
        {
            if (socket != null)
            {
                RemoveSocket(id);//移除同Key的Value
                _sockets[id] = socket;//添加
            }
        }
        /// <summary>
        /// 获取Socket
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static Socket GetSocket(string id)
        {
            if (_sockets.TryGetValue(id, out Socket socket))
                return socket;
            return null;
        }
        /// <summary>
        /// 移除Socket
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool RemoveSocket(string id)
        {
            return _sockets.Remove(id);
        }
}
 
// 使用SocketManager的例子
var socketManager = new SocketManager();
socketManager.AddSocket("socket1", new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
socketManager.AddSocket("socket2", new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp));
 
// 获取并使用一个Socket
Socket socket = socketManager.GetSocket("socket1");
// ... 对socket进行操作 ...
 
// 移除一个Socket
socketManager.RemoveSocket("socket2");

在这个例子中,SocketManager 类管理了一个字典 _sockets,用于存储不同的Socket对象。通过 AddSocket 方法添加新的Socket,GetSocket 方法获取指定ID的Socket,RemoveSocket 方法移除指定ID的Socket。使用字典的好处是可以快速通过ID访问或者移除Socket对象。


网站公告

今日签到

点亮在社区的每一天
去签到