问题描述
我在C#窗口表单应用程序中使用EasyModbus Nuget
.我正在尝试使用ModbusServer
通过RTU(实时更新)来获取更改的保持寄存器的地址值.
I am using EasyModbus Nuget
in C# Window Form Application. I am trying to fetch the changed Holding Register's Address Value through RTU(Real Time Update) using ModbusServer
.
下面的代码连接到服务器.
void Connect() {
ModbusClient client = null;
client = new ModbusClient("IP Address", 502);
client.Connect();
}
下面的代码获取保留寄存器下面给出的地址值.
client.ReadHoldingRegisters(10001, 1);
到目前为止,一切正常.
我正在阅读有关EasyModbus中实时更新的信息. 我发现此链接可以将保持寄存器的更改后的值自动发送给偶数处理程序.
I was reading about reading about Real Time Updates in EasyModbus. I found this link that can send the changed value of holding register automatically to the even handler.
现在,我有以下代码:
void Connect() {
ModbusServer ser = new ModbusServer();
ser.Port = Convert.ToInt32(Settings.Default.Port);
ser.Listen();
ser.HoldingRegistersChanged += Ser_HoldingRegistersChanged;
ModbusClient client = null;
client = new ModbusClient("IP Address", 502);
client.Connect();
}
private void Ser_HoldingRegistersChanged(int register, int numberOfRegisters)
{
}
运行时,出现以下错误.
发生此错误是因为我添加了ModbusServer代码.
This error is occurring because I added the ModbusServer code.
能否请您说明为什么会这样?
Can you please suggest why this is happening?
推荐答案
您的问题并不那么严重,您在此行遇到的主要问题
Your problem isn't so serious and your main problem in this line
ser.Listen();
因为您以前的服务器套接字仍在绑定中.
because your previous server socket is still in bound.
让我们看一下侦听套接字绑定时的情况吗?
let's take a looks when a listen socket is in bound ?
一个明显的原因是当您的侦听套接字发送/接收数据包时,但在极少数情况下,当操作系统不处于理想状态(100%cpu使用率等)时,就会发生这种情况,那么释放服务器套接字可能需要一分钟的时间才能释放.在这种情况下,当您再次运行服务器时
obvious reason is when your listening socket send/receive packets but in rare conditions it happens when OS is NOT in ideal condition(100 % cpu usage and etc) then Releasing server socket might takes a minute to be released. in this condition when you run your server again the exception
happens.because,因为我在以前的服务器套接字尚未发布之前说过.
happens.because , as i said before the previous server socket was not released yet.
解决方案
为不同的服务器套接字使用不同的端口
using different ports for different server sockets
或
仅使用一个仅启动一次的服务器套接字,并检查其是否已连接.
use only one server socket which is initiated only once and check if it's connected or not.
// create the socket
public static Socket listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// bind the listening socket to the port
IPAddress hostIP = (Dns.Resolve(IPAddress.Any.ToString())).AddressList[0];
IPEndPoint ep = new IPEndPoint(hostIP, port);
if(!listenSocket.IsBound){
listenSocket.Bind(ep);
// start listening
listenSocket.Listen(backlog);
}
// connect client
ModbusClient client = null;
client = new ModbusClient(hostIP , port);
client.Connect();
这篇关于一起编写ModbusClient和ModbusServer时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!