写入特定字节C#

时间:2017-03-14 07:37:05

标签: c# sockets byte

嘿,我写了一个简单的应用程序,即两个玩家可以互相聊天,基本上玩。

我的应用可以根据收到的数据类型执行不同的操作。

例如,如果玩家1向玩家2发送消息,则玩家2的客户端上的应用程序识别出它是消息类型,并且触发更新GUI的合适事件。

另一方面,如果玩家1进行移动,则玩家2的客户端应用识别它是移动类型并且做适当的事件。

所以它是数据的缓冲区

cat scan-config.xml | $CS_OMP -u $USER_NAME -w $USER_PASSWORD -i -X -

是否可以在Byte[] buffer = new Byte[1024]; 类型的数据(1 - MSG,2-MV)上写入,其余数据写入其余字节?或者是否有更好的方法来实现这个功能?

2 个答案:

答案 0 :(得分:5)

你可以使用BinaryReader / Writer。

例如:

发信人:

Byte[] buffer = new Byte[1024];

MemoryStream stream = new MemoryStream(buffer);
BinaryWriter writer = new BinaryWriter(stream);

writer.Write(1); // message type. (command)
writer.Write("Hi there");
writer.Write(3.1415);

使用stream.Position确定所写数据的长度。

接收器:

Byte[] buffer = new Byte[1024];

MemoryStream stream = new MemoryStream(buffer);
BinaryReader reader = new BinaryReader(stream);

int command = reader.ReadInt32();

switch(command)
{
    case 1:  // chat message
        string message = reader.ReadString();
        double whateverValue = reader.ReadDouble();
        break;

    case 2: // etc.
        break;
}

答案 1 :(得分:2)

如何整理这些数据呢?例如,如果你有一个包含“移动类型”数据的结构,你可以这样做:

发信人:

SOME_STRUCT data = new SOME_STRUCT();
int structSize = Marshal.SizeOf(data);
// you fill your struct here
var msgBytes = new Byte[1024];

IntPtr pointer = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(data, pointer, true);
Marshal.Copy(pointer, msgBytes, 0, size);
Marshal.FreeHGlobal(pointer);

接收器:

SOME_STRUCT receivedData = new SOME_STRUCT();
int structSize = Marshal.SizeOf(data);
// You receive your data here
var receivedBytes = msgBytes;

GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr pointer = handle.AddrOfPinnedObject();
Marshal.Copy(receivedBytes, 0, pointer, (int)structSize);