我正在编写一个在本地网络上工作的基于客户端/服务器的应用程序,为了在客户端和服务器之间交换数据,我创建了一个非常简单的NetworkCommand
对象,该对象被转换为byte[]
并使用TCP
or发送UDP
。
问题是end-of-packed
正确标记,
现在我已经使用byte[] {0, 0, 0}
和结束数据包标记,但这似乎在整个数据包本身中重复了太多次。
那么,我如何安全地标记end-of-packet
?
网络命令.cs
using System;
using System.IO;
namespace Cybotech.Common
{
public enum CommandType
{
NeedIP = 1,
IPData = 2,
}
public class NetworkCommand
{
public NetworkCommand(CommandType type, byte[] data)
{
Command = type;
Data = data;
}
public int Length
{
get { return Data.Length; }
}
public byte[] Data { get; set; }
public CommandType Command { get; set; }
public byte[] ToBytes()
{
MemoryStream stream = new MemoryStream();
//write the command type
byte[] data = BitConverter.GetBytes((int) Command);
stream.Write(data, 0, data.Length);
//append the length of the data
data = BitConverter.GetBytes(Length);
stream.Write(data, 0, data.Length);
//write the data
stream.Write(Data, 0, Data.Length);
//end of packer marker
data = new byte[] {0, 0, 0};
stream.Write(data, 0, 3);
data = stream.ToArray();
stream.Close();
stream.Dispose();
return data;
}
public static NetworkCommand CreateNetworkCommand(byte[] bytes)
{
MemoryStream stream = new MemoryStream(bytes);
BinaryReader reader = new BinaryReader(stream);
CommandType type = (CommandType) reader.ReadInt32();
int length = reader.ReadInt32();
byte[] data = reader.ReadBytes(length);
byte[] endMarker = reader.ReadBytes(3);
NetworkCommand cmd = new NetworkCommand(type, data);
reader.Close();
stream.Close();
stream.Dispose();
return cmd;
}
}
}