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.
tcpipSocket/Chat/Core/RoomListResponsePacket.cs

68 lines
1.7 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Core
{
public class RoomListResponsePacket : IPacket
{
public List<string> RoomNames { get; }
public RoomListResponsePacket(ICollection<string> roomNames)
{
RoomNames = new List<string>(roomNames);
}
public RoomListResponsePacket(byte[] buffer)
{
RoomNames = new List<string>();
for (int cursor = 2; cursor < buffer.Length;)
{
short roomNameSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
cursor += sizeof(short);
RoomNames.Add(Encoding.UTF8.GetString(buffer, cursor, roomNameSize));
cursor += roomNameSize;
}
}
public byte[] Serialize()
{
byte[] packetType = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)PacketType.RoomListResponse));
short dataSize = (short)(packetType.Length);
List<byte[]> temp = new List<byte[]>();
foreach (string item in RoomNames)
{
byte[] nameBuffer = Encoding.UTF8.GetBytes(item);
byte[] nameSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)nameBuffer.Length));
dataSize += (short)(nameBuffer.Length + nameSize.Length);
temp.Add(nameSize);
temp.Add(nameBuffer);
}
byte[] header = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(dataSize));
byte[] buffer = new byte[2 + dataSize];
int cursor = 0;
Array.Copy(header, 0, buffer, cursor, header.Length);
cursor += header.Length;
Array.Copy(packetType, 0, buffer, cursor, packetType.Length);
cursor += packetType.Length;
foreach (byte[] item in temp)
{
Array.Copy(item, 0, buffer, cursor, item.Length);
cursor += item.Length;
}
return buffer;
}
}
}