Skip to content

Commit

Permalink
[fix]修正死循环。网络层收不到数据时,ReceiveCommand可能进入无限死循环
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Apr 26, 2024
1 parent 48044f4 commit 78ee7e4
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
9 changes: 6 additions & 3 deletions NewLife.Modbus/Protocols/ModbusIp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,22 @@ protected virtual Packet ReceiveCommand()
{
// 设置协议最短长度,避免读取指令不完整。由于请求响应机制,不存在粘包返回。
var dataLength = 8; // 2+2+2+1+1
var count = 0;
Packet pk = null;
while (count < dataLength)
for (var i = 0; i < 8; i++)
{
// 阻塞读取
var pk2 = _client.Receive();
if (pk2 == null || pk2.Total == 0) continue;

if (pk == null)
pk = pk2;
else
pk.Append(pk2);

// 已取得请求头,计算真实长度
count = pk.Total;
var count = pk.Total;
if (count >= 6) dataLength = pk.ReadBytes(4, 2).ToUInt16(0, false);
if (count >= dataLength) break;
}

return pk;
Expand Down
8 changes: 5 additions & 3 deletions NewLife.Modbus/Protocols/ModbusRtuOverTcp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ protected override Packet ReceiveCommand()
{
// 设置协议最短长度,避免读取指令不完整。由于请求响应机制,不存在粘包返回。
var dataLength = 4; // 1+1+2
var count = 0;
Packet pk = null;
while (count < dataLength)
for (var i = 0; i < 3; i++)
{
// 阻塞读取
var pk2 = _client.Receive();
if (pk2 == null || pk2.Total == 0) continue;

if (pk == null)
pk = pk2;
else
pk.Append(pk2);

count = pk.Total;
if (pk.Total >= dataLength) break;
}

return pk;
Expand Down
8 changes: 5 additions & 3 deletions NewLife.Modbus/Protocols/ModbusRtuOverUdp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,19 @@ protected override Packet ReceiveCommand()
{
// 设置协议最短长度,避免读取指令不完整。由于请求响应机制,不存在粘包返回。
var dataLength = 4; // 1+1+2
var count = 0;
Packet pk = null;
while (count < dataLength)
for (var i = 0; i < 3; i++)
{
// 阻塞读取
var pk2 = _client.Receive();
if (pk2 == null || pk2.Total == 0) continue;

if (pk == null)
pk = pk2;
else
pk.Append(pk2);

count = pk.Total;
if (pk.Total >= dataLength) break;
}

return pk;
Expand Down

0 comments on commit 78ee7e4

Please sign in to comment.