手写ModbusTCP
ModbusTCP类
using System;
using System. Collections. Generic;
using System. Linq;
using System. Net;
using System. Net. Sockets;
using System. Text;
using System. Threading. Tasks;
namespace DeltaDemo
{
public class ModbusTCP
{
private Socket socket = null ;
public bool Connect ( string ip, int port)
{
socket = new Socket ( AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp) ;
try
{
socket. Connect ( IPAddress. Parse ( ip) , port) ;
}
catch ( Exception )
{
return false ;
}
return true ;
}
public void DisConnect ( )
{
if ( socket != null )
{
socket. Close ( ) ;
}
}
public byte SlaveId { get ; set ; } = 0x01 ;
public short [ ] ReadKeepReg ( ushort start, ushort length)
{
List< byte > SendCommand = new List < byte > ( ) ;
SendCommand. AddRange ( new byte [ ] { 0x00 , 0x00 } ) ;
SendCommand. AddRange ( new byte [ ] { 0x00 , 0x00 } ) ;
SendCommand. AddRange ( new byte [ ] { 0x00 , 0x06 } ) ;
SendCommand. Add ( SlaveId) ;
SendCommand. Add ( 0x03 ) ;
SendCommand. Add ( ( byte ) ( start / 256 ) ) ;
SendCommand. Add ( ( byte ) ( start % 256 ) ) ;
SendCommand. Add ( ( byte ) ( length / 256 ) ) ;
SendCommand. Add ( ( byte ) ( length % 256 ) ) ;
socket. Send ( SendCommand. ToArray ( ) ) ;
byte [ ] buffer = new byte [ 512 ] ;
int count = socket. Receive ( buffer, SocketFlags. None) ;
byte [ ] result = new byte [ count] ;
Array. Copy ( buffer, 0 , result, 0 , count) ;
if ( count == 9 + 2 * length)
{
if ( result[ 7 ] == 0x03 && result[ 8 ] == length * 2 )
{
short [ ] data = new short [ length] ;
for ( int i = 0 ; i < data. Length; i++ )
{
data[ i] = BitConverter. ToInt16 ( new byte [ ] { result[ 9 + 2 * i + 1 ] , result[ 9 + 2 * i] } ) ;
}
return data;
}
}
return null ;
}
}
}
主程序
using System;
using System. Collections. Generic;
using System. Linq;
using System. Text;
using System. Threading;
using System. Threading. Tasks;
namespace DeltaDemo
{
class Program
{
static void Main ( string [ ] args)
{
Console. WriteLine ( "Let's Begin" ) ;
if ( modbusTCP. Connect ( "192.168.1.204" , 502 ) )
{
Console. WriteLine ( "Connect Success" ) ;
while ( true )
{
short [ ] val = modbusTCP. ReadKeepReg ( 0 , 1 ) ;
if ( val != null )
{
Console. WriteLine ( "D0结果为:" + val[ 0 ] ) ;
}
else
{
Console. WriteLine ( "读取失败" ) ;
}
Thread. Sleep ( 1000 ) ;
}
}
else
{
Console. WriteLine ( "Connect Fail" ) ;
}
Console. ReadLine ( ) ;
}
private static ModbusTCP modbusTCP = new ModbusTCP ( ) ;
}
}
子线程如何调用UI线程不报错