I am a newbie in socket programming. I am developing a server client application. And I am using Asynchronous tcp ip socket. But now I am facing a problem. In my client side I am receiving my data by a 2kb byte array by beginReceive method. Its working perfectly if data size below or equals to 2 kb, but problem occurring when data size exceeding 2kb range. Please give me some solution.
This is perfectly normal - you shouldn't expect to get all the data in one call, whether you're using synchronous or asynchronous calls, and whether you have a lot of data or a little.
You should keep reading until the read call indicates that there's no more data - or until you've got everything you need. If your protocol needs more than one request/response on a connection, you should either length-prefix each message so that the other side knows how much to read, or have some sort of delimiter to indicate the end of a message. Length-prefixing is much easier when it's suitable, but it doesn't easily support streaming - you have to end up with length-prefixed "chunks" and a final chunk to indicate when you're done.
I agree with Jon's answer, wrt the fact that you shouldn't expect all your data in one read.
Here are some blogs that have helped me with this problem in the past: Aviad Ezra has an excellent series on Asynchronous Sockets:
- .NET Sockets - Two Way - Single Client
- .NET Sockets in Two Directions with Multiple Client Support
- Sending Typed (Serialized) Messages over .NET Sockets
This blog is particularly useful if you decide to go the length-prefixed route, the Author uses a MemoryStream as his temporary storage between reads: