Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using UnityEngine;
- namespace Utility.Packets
- {
- public class PacketSerializer
- {
- public static byte[] Build(UInt16 op_code, byte[] data = null)
- {
- byte[] op = BitConverter.GetBytes(op_code);
- UInt32 packet_length = Convert.ToUInt32(op.Length);
- byte[] header = BitConverter.GetBytes(packet_length);
- byte[] packet = new byte[op.Length + header.Length + data.Length];
- System.Buffer.BlockCopy(header, 0, packet, 0, header.Length);
- System.Buffer.BlockCopy(op, 0, packet, header.Length, op.Length);
- System.Buffer.BlockCopy(data, 0, packet, op.Length, data.Length);
- return packet;
- }
- public static string Beautify(byte[] packet)
- {
- string beautified = "{";
- for (int i = 0; i < packet.Length; i++)
- {
- if(i == packet.Length - 1)
- beautified += packet[i];
- else
- beautified += packet[i] + ", ";
- }
- return beautified + "}";
- }
- }
- public static class PacketBuilder {
- public static byte[] Pong()
- {
- return PacketSerializer.Build(OpCode.PONG);
- }
- public static byte[] Login(UInt16 _version, string _username, string _password)
- {
- byte[] username = System.Text.Encoding.UTF8.GetBytes(_username);
- byte[] password = System.Text.Encoding.UTF8.GetBytes(_password);
- UInt16 _user_len = Convert.ToUInt16(username.Length);
- UInt16 _pass_len = Convert.ToUInt16(password.Length);
- byte[] version = BitConverter.GetBytes(_version);
- byte[] user_len = BitConverter.GetBytes(_user_len);
- byte[] pass_len = BitConverter.GetBytes(_pass_len);
- byte[] packet = new byte[version.Length + user_len.Length + username.Length + pass_len.Length + password.Length];
- Buffer.BlockCopy(version, 0, packet, 0, version.Length);
- Buffer.BlockCopy(user_len, 0, packet, version.Length, user_len.Length);
- Buffer.BlockCopy(username, 0, packet, user_len.Length, username.Length);
- Buffer.BlockCopy(pass_len, 0, packet, username.Length, pass_len.Length);
- Buffer.BlockCopy(password, 0, packet, pass_len.Length, password.Length);
- Debug.Log(">> " + PacketSerializer.Beautify(packet));
- return PacketSerializer.Build(OpCode.LOGIN, packet);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement