c# - 将连接的套接字保存在字典中
问题描述
我正在尝试将连接的套接字保存在字典中,这样我的 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;
}
}
}
解决方案
天哪,我发现了问题......我使用以下方法调用它:
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;
}
推荐阅读
- reactjs - Formik - 名称和 ID 未传递到字段
- windows - Windows 打印 gpu/cpu/网络使用情况的命令
- mobile - OneSignal(推送通知总是展开)
- python - 应用程序崩溃而没有错误或关闭事件
- apache-nifi - 需要在 NiFi 中使用 1 个处理器而不是 5 个 FetchHDFS
- linux - 是否可以使用“which”命令执行“cd”命令?(我想将这两个命令合二为一。)
- google-chat - [Google Chatbot]发布聊天机器人时出现未列出的错误
- google-smart-home - google Local home 本地 SDK 设备发现
- tensorflow - 我应该如何使用 TF 模型花园 beta API?
- r - 使用 drm 函数在一张图上绘制多条拟合曲线