我的建议是先创建一个Message
类,这将是“兑换”从和到byte[]
类型。然后,您可以创建一个NetStream
,该NetStream
源自Stream
,并使用它通过指定的Socket
发送数据。这是一个易于维护的解决方案,根本不需要任何关于套接字通信的额外知识。
代码示例:
// include these namespaces :
using System;
using System.Collections.Generic;
public class Message
{
int m_MessageLength;
// your other fields
char m_OtherField1;
char m_OtherField2;
char m_OtherField3;
char m_OtherField4;
// message content as I assume is string
string m_MessageContent;
public Message(string message, int field1, int field2, int field3, int field4)
{
m_MessageConten = message;
m_OtherField1 = field1;
m_OtherField2 = field2;
m_OtherField3 = field3;
m_OtherField4 = field4;
}
public static explicit operator byte[](this Message message)
{
List<byte> buffer = new List<byte>();
// 4 fields each 2bytes wide gives us 16 bytes
// ASCII character is 7 bits wide but is packed into 8 bits which is 1byte
// gives us the result of (length_of_message * 1byte == length_of_message)
buffer.AddRange(BitConverter.GetBytes(8 + m_MessageContent.Length));
buffer.AddRange(BitConverter.GetBytes(m_OtherField1));
buffer.AddRange(BitConverter.GetBytes(m_OtherField2));
buffer.AddRange(BitConverter.GetBytes(m_OtherField3));
buffer.AddRange(BitConverter.GetBytes(m_OtherField4));
buffer.AddRange(Encoding.ASCII.GetBytes(m_MessageContent));
return buffer.ToArray();
}
}
有了这个对象,你可以只使用Socket.Send
方法:
Message message = new Message("hello world", 1, 3, 3, 7);
meSocket.Send((byte[])message);
如果这还不够,只是让我知道,我会更新这个答案与更多的细节。
从接收数据读取四个字节到一个数组中。使用BitConvert将数组转换为int或uint。 BitConverter.ToUInt32(阵列,0);您需要验证长度是否大于2^31(无符号整数) – jdweng