首页 > 解决方案 > 将连接的套接字保存在字典中

问题描述

我正在尝试将连接的套接字保存在字典中,这样我的 API 就不必每次都创建新连接。我的问题是套接字被处理掉了。因此,当我第二次调用 GetConnection() 时,socket.connected 为 false 并且 socket.Available.Message 为“无法访问已处置的对象。对象名称:'System.Net.Sockets.Socket'。”。

public static class ModbusSocket
{
    private static Dictionary<IPAddress, Socket> socketList;


    public static Socket GetConnection(string server, int port)
    {

        if (socketList is null)
        {
            socketList = new Dictionary<IPAddress, Socket>();
        }
        IPAddress iPAddress = IPAddress.Parse(server);

        if (socketList.ContainsKey(iPAddress))
        {
            var socket = socketList[iPAddress];
            if (socket.Connected)
            {
                return socket;
            }
            else
            {
                socketList.Remove(iPAddress);                    
                socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint ipe = new IPEndPoint(iPAddress, port);
                socket.Connect(ipe);
                socketList.Add(iPAddress, socket);
                return socket;

            }
        }
        else
        {
            Socket socket = new Socket(iPAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe = new IPEndPoint(iPAddress, port);
            socket.Connect(ipe);
            socketList.Add(iPAddress, socket);
            return socket;
        }
    }
}

标签: c#asp.netsocketsasp.net-coretcp

解决方案


天哪,我发现了问题......我使用以下方法调用它:

        using (Socket s = ModbusSocket.GetConnection(hostIp, port))
        {
            var telegram = new Telegram();
            telegram.Set(0, AddressConst.PositionWindow, 4);
            var response = telegram.SendAndReceive(s);
            var result = BitConverter.ToInt32(new byte[] { response.Byte19, response.Byte20, response.Byte21, response.Byte22 }, 0);
            return result;
        }

推荐阅读