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/EnterRoomRequestPacket.cs

59 lines
1.6 KiB

2 years ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Core
{
public class EnterRoomRequestPacket : IPacket
{
public string RoomName { get; private set; }
public EnterRoomRequestPacket(string roomName)
{
RoomName = roomName;
}
public EnterRoomRequestPacket(byte[] buffer)
{
int cursor = 2;
short roomNameSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
cursor += sizeof(short);
RoomName = Encoding.UTF8.GetString(buffer, cursor, roomNameSize);
}
public byte[] Serialize()
{
// 2bytes header
// data: 2bytes packetType + 2bytes id size + id + 2bytes nickname size + nickname
byte[] packetType = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)PacketType.EnterRoomRequest));
byte[] roomName = Encoding.UTF8.GetBytes(RoomName);
byte[] roomNameSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)roomName.Length));
short dataSize = (short)(packetType.Length + roomName.Length + roomNameSize.Length);
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;
Array.Copy(roomNameSize, 0, buffer, cursor, roomNameSize.Length);
cursor += roomNameSize.Length;
Array.Copy(roomName, 0, buffer, cursor, roomName.Length);
return buffer;
}
}
}