I'm using following code
for(int i =0; i < 100; i++){
TcpSocket.Send(getModifiedData(MyData));
}
The code is called too much, maybe one time per every tick.
The socket is connected to my local machine(127.0.0.1) so there is no latency, pocket loss etc.
The first messages are just fine but I don't get some pockets later.
Now if I change that code to following then all my pockets are sent and recieved!
for(int i =0; i < 100; i++){
Console.WriteLine("SendData > " + TcpSocket.Send(getModifiedData(MyData)));
}
And yes I'm pretty sure because I have tested this more than 10 times. Logging to console with WriteLine
method fixes this issue.
I'm totally lost with this very weird problem.
Note that following code helps to send more pockets than first default code posted in question.
for(int i =0; i < 100; i++){
System.Threading.Thread.Sleep(1);
TcpSocket.Send(getModifiedData(MyData));
}
But even with sleeping about 10% of my pockets are lost!
I found logging to console best solution which sends 100% of pockets without loss.
Receiver code :
// variables
static NetworkStream^ NS;
// CClient::NS = gcnew NetworkStream(CClient::sender);
//
Dictionary<String^, Object^>^ x = (Dictionary<String^, Object^>^)PClientFuncs::Deserialize(CClient::NS);
//method
Object^ PClientFuncs::Deserialize(Stream^ s){
try{
BinaryFormatter^ formatter = gcnew BinaryFormatter();
DeflateStream^ serializationstream = gcnew DeflateStream(s, CompressionMode::Decompress);
return formatter->Deserialize(serializationstream);
}
catch (Exception^) {
return nullptr;
}
}
So What's the problem ? Why this happening and how to fix it ?
You are assuming that TCP sends data in packets. This is not true. TCP presents you a contiguous stream of bytes. This means that what you receive is not necessarily received in the same "chunks" as you send it. Probably, that is confusing your receiver.
The best way to deal with this is to not write a TCP-based application. Use some higher-level construct like HTTP. Libraries for clients and servers are available. They solve a lot of problems for you.