C# 在C语言中通过TCP套接字方法发送位型数据#
这是我第一次在这个平台上提问。 请随意指出我应该做什么或避免做什么,以变得更好,谢谢 我正试图向MES(制造执行系统)发送一个Struct对象,以更改我的工作站的状态。 以下是数据结构(2.2)的说明: 下面C#中的代码就是我所做的。我确信我连接了MES系统,但状态没有改变,我想原因可能与我传输的数据格式有关C# 在C语言中通过TCP套接字方法发送位型数据#,c#,serialization,tcpclient,C#,Serialization,Tcpclient,这是我第一次在这个平台上提问。 请随意指出我应该做什么或避免做什么,以变得更好,谢谢 我正试图向MES(制造执行系统)发送一个Struct对象,以更改我的工作站的状态。 以下是数据结构(2.2)的说明: 下面C#中的代码就是我所做的。我确信我连接了MES系统,但状态没有改变,我想原因可能与我传输的数据格式有关 using System; using System.Net.Sockets; using System.Text; using System.Threading; using Syst
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using TcpClient = NetCoreServer.TcpClient;
//the Struct of data
[StructLayout(LayoutKind.Sequential, Pack = 8)]
public struct StateOfRobotino
{
public int ResourceID;
public byte SPSType;
public byte State_info;
}
StateOfRobotino robotino10 = new StateOfRobotino();
robotino10.ResourceID = 10;
robotino10.SPSType = 2;
robotino10.State_info = 0b10000001; //MES mode, Auto
byte[] b_robotino10 = getBytes(robotino10);
//Convert Struct type to byte array through Marshal
byte[] getBytes(StateOfRobotino str)
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
我怀疑的一点是我的结构中的第三个数据,我能用一个字节(State_info)来表示8位的数据吗?如果没有,我该怎么办?或者有没有其他方法可以尝试传输此类数据?
谢谢。获取字节数组的编组方法应该可以工作 现在转到您的数据结构:
ResourceID Int 0
SPSType Byte 2
Auto Mode Bit 3.0
... Bit 3.n
MES Mode Bit 3.7
请注意包含0、2和3.x的数字列
ResourceID
看起来占用字节0和1。Int
中的两个字节表示PLC为16位。C#的int
是32位的,占四个字节。您需要明确指定Int16
或UInt16
(可能是无符号的UInt16
,除非MES希望PLC提供负数)
它们也被称为short
或ushort
,但在处理外部系统时,最好通过指定16位来更加明确,以尽量减少混淆
SPSType
只是一个字节
3.0。。。3.7
。这是占用字节3的8位(0..7)的表示法。这意味着,是的,您需要发送一个包含所有位的字节。请记住位0是最右边的位,因此0b0000001
是自动模式,0b10000000
是MESMode
具体来说,感谢您对4字节零和数据结构(INT实际上是16位(2字节))的提示。