// 本文使用的服务器为Modbus 仿真服务器Modbus Salve
<1>.同步方法
byte[] buffer = new byte[1024];
Socket clinetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 502);
clinetSocket.Connect(ipEnd);
// 000020-Rx:00 86 00 00 00 06 01 03 00 00 00 0A
/* 00 86 通信标识符
* 00 00 Modbus 协议
* 00 06 后面字节个数
* 01 站号
* 03 功能码
* 00 00 起始地址
* 00 0A 操作数量
*/
byte[] sendMsg = { 0x00, 0x86, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
clinetSocket.Send(sendMsg, sendMsg.Length, SocketFlags.None);
// System.Threading.Thread.Sleep(200);
int mlength = clinetSocket.Receive(buffer, SocketFlags.None);
// 不显示
// txtSend.Text = Encoding.Unicode.GetString(buffer, 0, mlength);
// 可以使用但是会给数组加 00-01-02
txtSend.Text = BitConverter.ToString(buffer, 0, mlength);
// 不知道转成什么鬼了
// txtSend.Text = Convert.ToBase64String(buffer, 0, mlength);
<2>.异步方法
byte[] buffer = new byte[1024];
byte[] sendMsg = { 0x00, 0x86, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
///
/// 异步不读取开始按钮
///
///
///
private void btnAsynConnect_Click(object sender, EventArgs e)
{
Socket clinetSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 502);
clinetSocket.Connect(ipEnd);
clinetSocket.BeginSend(sendMsg, 0, sendMsg.Length, SocketFlags.None, CallBack, clinetSocket);
}
///
/// 发送的回调方法
///
///
private void CallBack(IAsyncResult ar)
{
var clinet = ar.AsyncState as Socket;
clinet.BeginReceive(buffer, 0, 29, SocketFlags.None, ReciveCallback, clinet);
}
///
/// 接受的回调方法
///
///
private void ReciveCallback(IAsyncResult ar)
{
var myclinet = ar.AsyncState as Socket;
myclinet.EndReceive(ar);
txtRecive.Invoke(new Action(() =>
{
txtRecive.Text = BitConverter.ToString(buffer,0,29);
}
)
);
// 工控中最常见的循环读取方法
myclinet.BeginSend(sendMsg, 0, sendMsg.Length, SocketFlags.None, CallBack, myclinet);
}