Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Codeproject,

I currently have a TCP Server and Client, threaded that is.

The problem I am facing is that TCP only allows bytes to send and receive.
But it's not a problem, in fact, it's the beauty in it. But, it's impossible to
determine client and server sided how many bytes you send without having a limit,
for instance '4096'. So, what if I would want to sent a class, for instance:

C#
public class Email
{
  string Mail { get; set;}
  string Recept { get; set; }
  string Sent { get; set; }
  
  public Email()
  {
    
  }

  public SetEmail(string Receptant, string Sender, string Message)
  {
       Mail = Message;
       Recept = Receptant;
       Sent = Sender;
   }
}


Basically, if I would use XML Serializer to serialize this class into a StringBuilder, than took the MemoryStream and made a byte[] out of it, it was possible for me to send a whole class, right? No, not at all. Since Mail, Recept, and Sent, are variabels, they can and will be changed. So assuming my message was a bit longer than 4000 characters, I would already have a problem. So my question is, if it's possible to determine how big an incoming byte array is, how would I do that? Or, does anyone have any other suggestions?
Posted
Updated 9-Mar-13 5:46am
v2

1 solution

TCP by itself is only a transport layer. Your problem is, that you forgot to implement the layer above it: the application layer (see: http://en.wikipedia.org/wiki/Internet_protocol_suite[^]).
More precisely, you experienced it correctly, you can not relay only on the stream you can write/read in a TCP communication, you have to implement a protocol, your application protocol above it. All internet applications use some sort of binary or text based protocol, some are complicated, some are more simple. In general these protocols define message formats. In your case a simple one could be like this (A sender, B receiver):
A -> B : I will send you a message of 4541 bytes
B -> A : Ok, I am ready
A -> B : [send those 4541 bytes]
B -> A : I got it
(of course, this is "english", but you could use predefined structures serialized to byte stream - except for the actual content.)

Following articles will give you the highlights of your possibilities in c#.
A Complete TCP Server/Client Communication and RMI Framework in C# .NET - Implementation[^]
Design and Implementation of a High-performance TCP/IP Communications Library[^]
 
Share this answer
 
Comments
Yvar Birx 9-Mar-13 16:50pm    
Many thanks to your informative answer, I will look at these links and I already have an idea on how to make it work.

Cheers! :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900