This blog shows how to send and receive data via TCP/IP using Socket in .NET Framework. There are methods Socket.Send and Socket.Receive.
Socket.Send Method
Send method sends data from your buffer to a connected Socket. When you call the Send method it returns number of bytes which were sent. But it doesn't mean that the bytes were already received by the other side, it only means that the data were stored in a socket buffer and the socket will be trying to send them. If the socket buffer is full a WouldBlock error occurs. You should wait for a while a try to send the data again.
Following method sends size bytes stored in the buffer from the offset position. If the operation lasts more than timeout milliseconds it throws an exception.
- public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
- {
- int startTickCount = Environment.TickCount;
- int sent = 0; // How many bytes is already sent
- do
- {
- if (Environment.TickCount > startTickCount + timeout)
- throw new Exception("Timeout.");
- try
- {
- sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
- }
- catch (SocketException ex)
- {
- if (ex.SocketErrorCode == SocketError.WouldBlock ||
- ex.SocketErrorCode == SocketError.IOPending ||
- ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
- {
- // Socket buffer is probably full, wait and try again
- Thread.Sleep(30);
- }
- else
- throw ex; // Any serious error occurr
- }
- } while (sent < size);
- }

Santhakumar MunuswamyPosted Apr 28, 2015, 2:45 PM
good work