[iurl=#ReadWrite]Write/Read[/iurl]
I've made my own PacketWriter/PacketReader to use for Sockets that send data with an Byte array.
The byte array doesn't got a fixed size so whenever you write it makes the array bigger.
[Anchor=ReadWrite]
You can read/write:[/anchor]
Download Here
I know i'm not so good with explaining...
I've made my own PacketWriter/PacketReader to use for Sockets that send data with an Byte array.
The byte array doesn't got a fixed size so whenever you write it makes the array bigger.
Code:
PacketWriter writer = new PacketWriter(0);
writer.Write("Hello Server");
writer.Write(56);
ClientSocket.Send(writer.GetPacket);
Code:
PacketReader reader = new PacketReader(socketCollection[e.SourceIP].Get());
switch (reader.PacketID)
{
case 0: //Greetings from Client
string message = reader.ReadString();
int RandomInt = reader.ReadInt();
break;
}
Writer:
Reader:
Code:
private byte[] PacketBytes;
private int offset;
private ushort packetID;
private Encoding encoding = Encoding.ASCII;
public byte[] GetPacket
{
get { return PacketBytes; }
}
public int ByteLength
{
get { return PacketBytes.Length; }
}
public PacketWriter(ushort PacketID, Encoding Encoding)
{
PacketBytes = new byte[0];
offset = 0;
packetID = PacketID;
this.encoding = Encoding;
Write(packetID);
}
public PacketWriter(ushort PacketID)
{
PacketBytes = new byte[0];
offset = 0;
packetID = PacketID;
Write(packetID);
}
public void Write(int value)
{
ResizeArray(4);
byte[] bytes = BitConverter.GetBytes(value);
Buffer.BlockCopy(bytes, 0, PacketBytes, offset, 4);
offset += 4;
}
public void Write(string value)
{
byte[] bytes = encoding.GetBytes(value);
ResizeArray(bytes.Length);
Write(bytes.Length);
Buffer.BlockCopy(bytes, 0, PacketBytes, offset, bytes.Length);
offset += bytes.Length;
}
Reader:
Code:
private byte[] PacketStream;
private int offset;
private ushort packetID;
private Encoding encoding = Encoding.ASCII;
public int ByteLength
{
get { return PacketStream.Length; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (byte b in PacketStream)
{
sb.Append(string.Format("{0:X2}", b) + " ");
}
return sb.ToString();
}
public ushort PacketID
{
get { return packetID;}
}
public PacketReader(byte[] Packet)
{
PacketStream = Packet;
offset = 0;
packetID = ReadUShort();
}
public PacketReader(byte[] Packet, Encoding Encoding)
{
PacketStream = Packet;
offset = 0;
packetID = ReadUShort();
this.encoding = Encoding;
}
public int ReadInt()
{
int i = BitConverter.ToInt32(PacketStream, offset);
offset += 4;
return i;
}
public string ReadString()
{
int length = ReadInt();
string s = encoding.GetString(PacketStream, offset, length);
offset += length;
return s;
}
You can read/write:[/anchor]
- long
- ulong
- double
- int
- uint
- float
- short
- ushort
- char
- byte
- bool
- byte array
- string
Download Here
I know i'm not so good with explaining...