怎样把数据打包用socket发送?
public byte flag = 0x80;
public byte flag2 = 0;
public ushort uscmd = 0xC664;
public int datalen = 40;
将这几个变量打包成一个 buffer 发送,buffer 数据如下:
flag+flag2+uscmd+datalen
要发送后的格式为byte[]或二进制的,该怎么写?
------解决方案-------------------- private void button1_Click(object sender, EventArgs e)
{
Data data = new Data();
data.flag = 1;
data.flag2 = 2;
data.uscmd = 66;
data.datalen = 435;
byte[] buffer = new byte[data.Size];
IntPtr ptr = Marshal.AllocHGlobal(data.Size);
Marshal.StructureToPtr(data, ptr, true);
Marshal.Copy(ptr, buffer, 0, buffer.Length);
MessageBox.Show(buffer.Length.ToString());
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Data
{
public byte flag;
public byte flag2;
public ushort uscmd;
public int datalen;
public int Size
{
get { return 8; }
}
}
------解决方案--------------------MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.write(flag);
writer.write(flag2);
writer.write(uscmd);
writer.write(datalen);
byte[] buffer = stream.ToArray();
writer.close();
最简单的方法大概如此。。手边没有 Visaul studio。。可能有一些拼写错误。
------解决方案--------------------
查一下socket的send函数声明,应该是3个参数:
IPAddress dest,Byte[] Buffer,SocketOption op.
,第一个参数可能没有如果是tcp的话
首先
connect,然后构造buffer调用send就OK啦,so easy