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.
74 lines
2.2 KiB
74 lines
2.2 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Core
|
|
{
|
|
public class ChatPacket : IPacket
|
|
{
|
|
public string Message { get; private set; }
|
|
public string NickName { get; private set; }
|
|
|
|
public ChatPacket(string nickname, string message)
|
|
{
|
|
NickName = nickname;
|
|
Message = message;
|
|
}
|
|
|
|
public ChatPacket(byte[] buffer)
|
|
{
|
|
int cursor = 2;
|
|
|
|
short messageSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
|
|
cursor += sizeof(short);
|
|
|
|
Message = Encoding.UTF8.GetString(buffer, cursor, messageSize);
|
|
cursor += messageSize;
|
|
|
|
short nicknameSize = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(buffer, cursor));
|
|
cursor += sizeof(short);
|
|
|
|
NickName = Encoding.UTF8.GetString(buffer, cursor, nicknameSize);
|
|
}
|
|
|
|
public byte[] Serialize()
|
|
{
|
|
// 2bytes header
|
|
// data: 2bytes packetType + 2bytes id size + id + 2bytes nickname size + nickname
|
|
|
|
byte[] packetType = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)PacketType.Chat));
|
|
byte[] message = Encoding.UTF8.GetBytes(Message);
|
|
byte[] messageSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)message.Length));
|
|
byte[] nickname = Encoding.UTF8.GetBytes(NickName);
|
|
byte[] nicknameSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder((short)nickname.Length));
|
|
|
|
short dataSize = (short)(packetType.Length + message.Length + messageSize.Length + nickname.Length + nicknameSize.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(messageSize, 0, buffer, cursor, messageSize.Length);
|
|
cursor += messageSize.Length;
|
|
|
|
Array.Copy(message, 0, buffer, cursor, message.Length);
|
|
cursor += message.Length;
|
|
|
|
Array.Copy(nicknameSize, 0, buffer, cursor, nicknameSize.Length);
|
|
cursor += nicknameSize.Length;
|
|
|
|
Array.Copy(nickname, 0, buffer, cursor, nickname.Length);
|
|
|
|
return buffer;
|
|
}
|
|
}
|
|
}
|
|
|