TCPSocket Sends Extra Byte - Sometimes

This is a strange one.

I have a 32-bit Windows desktop app that I use to test Modbus code before I incorporate it into my services. I recently started developing code to use ModbusTCP. This is actually easier than ModbusRTU (serial) and involves sending a simple data packet to the device IP on port 502. The packet in my case is 12 bytes.

When initially developing I was getting the bugs out and sorting out the data parsing, so I would send a message, debug, restart. No issues.

Once this was sorted out I started sending requests repeatedly, and only about one out of four had responses. It was random too. I added some code to dump the outgoing and incoming messages and everything looked good.

I have a third-party Modbus test program and it shows the same data working just fine - every time.

So I downloaded WireShark and started capturing. What I found was disturbing. The Modbus test program produced consistent messages and Wireshark recognized them as ModbusTCP protocol. My app sometimes did this sometimes, but more frequently it send more bytes than were in my message. Here is an example of the two messages sent. The first two bytes vary as they are message ID bytes.

Modbus Tester: 70 00 00 00 06 01 03 00 30 00 02
My App: 77 c2 97 00 00 00 06 01 03 00 30 00 02

The c2 in my data stream was NOT in the original message. And that inserted byte seems to be either c2 or c3, nothing else.

Here is the code that sends the data:

try

MB.Write strDataIn
MB.Flush

Return OK

Catch e as NetworkException
Return SendFailed
end

MB is my TCPSocket.

I also wrote a quick app to receive the data rather than the Modbus device and the results were the same.

I am using 2024r3.1. I have just downloaded 2025r1 and will try that, but I am not hopeful.

I have used TCPSockets several for service apps over the past few years and this did not seem to be an issue. I really am puzzled and bothered. Does anyone have any ideas on what I might try next?

More digging and greatly relieved. The extra byte is coming in when building the string but this was not showing in my test code. I have yet to find it, but I feel much better about the TCPSocket.

I KNEW it had to be my stupidity.

1 Like

I think your issue is to do with the encoding of your string. You actually have 2 extra bytes in your example c297 see for more info.

The issue turned out to be using Chr, not ChrB (now ChrByte), to encode the string. I knew this (as I have done this thing before) but stupidity is a strong force in the universe. This will not soon be forgotten.

Thanks for the reply.

2 Likes

I’ve made that mistake more times than I care to admit.