So my problem is, I am developing a client server application, and i wonder how to prevent packet receiving problems [such the one above]Quote:
The Problem
One of the most common beginner mistakes for people designing protocols for TCP/IP is that they assume that message boundaries are preserved. For example, they assume a single "Send" will result in a single "Receive".
Some TCP/IP documentation is partially to blame. Many people read about how TCP/IP preserves packets - splitting them up when necessary and re-ordering and re-assembling them on the receiving side. This is perfectly true; however, a single "Send" does not send a single packet.
Local machine (loopback) testing confirms this misunderstanding, because usually when client and server are on the same machine they communicate quickly enough that single "sends" do in fact correspond to single "receives". Unfortunately, this is only a coincidence.
This problem usually manifests itself when attempting to deploy a solution to the Internet (increasing latency between client and server) or when trying to send larger amounts of data (requiring fragmentation). Unfortunately, at this point, the project is usually in its final stages, and sometimes the application protocol has even been published!
True story: I once worked for a company that developed custom client/server software. The original communications code had made this common mistake. However, they were all on dedicated networks with high-end hardware, so the underlying problem only happened very rarely. When it did, the operators would just chalk it up to "that buggy Windows OS" or "another network glitch" and reboot. One of my tasks at this company was to change the communication to include a lot more information; of course, this caused the problem to manifest regularly, and the entire application protocol had to be changed to fix it. The truly amazing thing is that this software had been used in countless 24x7 automation systems for 20 years; it was fundamentally broken and no one noticed.
Here is the way i send a message to the server from my simple client
[CLIENT]
Code:
TcpClient Client = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000); private void btnSend_Click(object sender, EventArgs e) { NetworkStream clientStream = Client.GetStream(); ASCIIEncoding encoder = new ASCIIEncoding(); byte[] buffer = encoder.GetBytes(textMessage.Text); clientStream.Write(buffer, 0, buffer.Length); clientStream.Flush(); }
Code:
string msg = "1001:UN=badguy4you&&PW=5001"; //1001 is the id
Code:
private void OnReceivePacket(byte[] buffer, IE Client) { try { int ID; string V = Encoding.ASCII.GetString(buffer).Split(':')[0]; int.TryParse(V, out ID); switch (ID) { case 1001: Append("Login Packet Received"); break; case 1002: //Other IDs break; default: break; } } catch { } }
Also What is the difference between Encoding.ASCII and Encoding.UTF8 ?