I'm going to assume that you have developed your own protocol and expect datagrams with a predetermined size, and you want to protect yourself from rogue packets.
Since performance seems like a problem and you want to avoid exceptions, I would look at receiver overload , which returns unhandled instead of exception errors. The MSDN documentation (wrong?) States that this method will throw an exception as well, but I don't think so. It is definitely worth a try.
SocketError error; byte[] buffer = new byte[512]; // Custom protocol max/fixed message size int c = this.Receive(buffer, 0, buffer.Length, SocketFlags.None, out error); if (error != SocketError.Success) { if(error == SocketError.MessageSize) { // The message was to large to fit in our buffer } }
Use a buffer of a predetermined size and use overload to check the SocketError error code to determine if the reading was interrupted or if you deleted the package.
If, however, your own protocol can send datagrams of unknown sizes to the maximum datagram size limit, you have no choice but to allocate a buffer large enough for the maximum packet (65k) (you can use a buffer pool to avoid memory problems depending on your code).
Also check out the SocketFlags enumeration , it contains some elements that may interest you, such as Partial and Peek members.
source share