I just spent a lot of hours reading on TCP servers and my desired protocol, which I tried to implement, and finally everything worked fine. I noticed that the code looks like absolute bollocks (is this the right use? Im not a brit) and would like to get some feedback on its optimization, mainly for reuse and readability.
The packet formats are always int, int, int, string, string.
try
{
BinaryReader reader = new BinaryReader(clientStream);
int packetsize = reader.ReadInt32();
int requestid = reader.ReadInt32();
int serverdata = reader.ReadInt32();
Console.WriteLine("Packet Size: {0} RequestID: {1} ServerData: {2}", packetsize, requestid, serverdata);
List<byte> str = new List<byte>();
byte nextByte = reader.ReadByte();
while (nextByte != 0)
{
str.Add(nextByte);
nextByte = reader.ReadByte();
}
string string1 = Encoding.UTF8.GetString(str.ToArray());
str.Clear();
nextByte = reader.ReadByte();
while (nextByte != 0)
{
str.Add(nextByte);
nextByte = reader.ReadByte();
}
string string2 = Encoding.UTF8.GetString(str.ToArray());
Console.WriteLine("String1: {0} String2: {1}", string1, string2);
MemoryStream stream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(stream);
writer.Write((int)(1));
writer.Write((int)(requestid));
byte[] buffer = stream.ToArray();
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
I will also deal with other types of packages that are formatted the same way (int / int / int / str / str), but with different values. Maybe I could create a package class, but that is a bit beyond my knowledge of how to apply it to this scenario. If that matters, this is the protocol that I am implementing.
http://developer.valvesoftware.com/wiki/Source_RCON_Protocol
user470760