Fazi Fazi - 11 months ago 138
C# Question

TCP Sokcet receiving error (bug)


I was working on a program that will transfer multiple "data types" over a single port. But the code I have written contains a bug that I can not solve.


The problem is that code:

public void Receiver()
while (active)
//Receive metadata
byte[] Metadata_Raw = new byte[1024];
int Metadata_Raw_Lenght = Client.Receive(Metadata_Raw);

//Exit if disconnected
if (!(Metadata_Raw_Lenght > 0))

//Convert metadata to string
string Metadata = System.Text.Encoding.UTF8.GetString(Metadata_Raw, 0, Metadata_Raw_Lenght);

//Get info from metadata
Match MetaData_Formated = rgx.Match(Metadata);

//Exit if metadata is not valid
if (!MetaData_Formated.Success)

//Get type, receive it and fire the event
switch (MetaData_Formated.Groups[1].Value)
case "string":
int totalLenght = int.Parse(MetaData_Formated.Groups[2].Value);
byte[] tmpData = new byte[totalLenght];
int len = Client.Receive(tmpData);
if (len < totalLenght)
DEvents.StringReceived(username, Encoding.UTF8.GetString(tmpData));
Debug.WriteLine("Unsupported type.");

receives the first 2 messages fine (string,12,,> and Kako si kaj?). But when that is finished the next receive (int Metadata_Raw_Lenght = Client.Recieve(Metadata_Raw)) sets the lenght (Metadata_Raw_Lengt) to 1 and thats when the code starts bugging (not receiving any messages etc.).


I would love if you can tell me what's wrong with it. Thank you in advance.

Answer Source

TCP does not use "Messages", it uses streams. So once send does not equal one receive, you could have "messages" combined together or split apart.

You need to create your own message system, which it looks like you have started with Metadata, but you need to keep calling Read until you have received all of the metadata and you need to be careful you have not read extra information.

See TCP Message Framing by Stephen Cleary for a deeper explanation of what is going wrong.