You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.2 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace STcpHelper.Packet
{
public class STcpTextPacket : ISTcpPacket
{
public string Text { get; private set; }
public STcpTextPacket(string text)
{
this.Text = text;
}
public STcpTextPacket(byte[] dataBuffer)
{
int cursor = 0;
short textSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(dataBuffer, cursor));
cursor += sizeof(short);
this.Text = Encoding.UTF8.GetString(dataBuffer, cursor, textSize);
}
public byte[] Serialize()
{
byte[] text = Encoding.UTF8.GetBytes(Text);
byte[] textSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)text.Length));
// 4byte header
STcpPacketHeader header = new STcpPacketHeader(PacketType.TEXT, text.Length + textSize.Length);
// [2bytes text size][n bytes text]
return SBufferHelper.GetBuffer(4 + textSize.Length + text.Length, header.Serialize(), textSize, text);
}
}
}