Send and Receive Data Using Socket

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.
  1. public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)  
  2. {  
  3.   int startTickCount = Environment.TickCount;  
  4.   int sent = 0;  // How many bytes is already sent  
  5.   do
  6.   {  
  7.     if (Environment.TickCount > startTickCount + timeout)  
  8.       throw new Exception("Timeout.");  
  9.     try 
  10.     {  
  11.       sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);  
  12.     }  
  13.     catch (SocketException ex)  
  14.     {  
  15.       if (ex.SocketErrorCode == SocketError.WouldBlock ||  
  16.           ex.SocketErrorCode == SocketError.IOPending ||  
  17.           ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)  
  18.       {  
  19.         // Socket buffer is probably full, wait and try again  
  20.         Thread.Sleep(30);  
  21.       }  
  22.       else  
  23.         throw ex;  // Any serious error occurr  
  24.     }  
  25.   } while (sent < size);  

To call the Send method use following code snippet (suppose the static Send method is defined in MyClass class). TCP/IP socket can be obtained using TcpClient class. Use TcpClient.Client property to get the underlying Socket (this property is public since .NET Framework 2.0).
  1. Socket socket = tcpClient.Client;  
  2. string str = "Hello world!";  
  3. try  
  4. // Sends the text with timeout 10s  
  5.   MyClass.Send(socket, Encoding.UTF8.GetBytes(str), 0, str.Length, 10000);  
  6. }  
  7. catch (Exception ex) { /* ... */ } 
Socket.Receive Method

Receive method receives data from a bound Socket to your buffer. The method returns number of received bytes. If the socket buffer is empty a WouldBlock error occurs. You should try to receive the data later.

Following method tries to receive size bytes into the buffer to the offset position. If the operation lasts more than timeout milliseconds it throws an exception.
  1. public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)  
  2. {  
  3.   int startTickCount = Environment.TickCount;  
  4.   int received = 0;  // How many bytes is already received  
  5.   do 
  6.   {  
  7.     if (Environment.TickCount > startTickCount + timeout)  
  8.       throw new Exception("Timeout.");  
  9.     try 
  10.     {  
  11.       received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);  
  12.     }  
  13.     catch (SocketException ex)  
  14.     {  
  15.       if (ex.SocketErrorCode == SocketError.WouldBlock ||  
  16.           ex.SocketErrorCode == SocketError.IOPending ||  
  17.           ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)  
  18.       {  
  19.         // Socket buffer is probably empty, wait and try again  
  20.         Thread.Sleep(30);  
  21.       }  
  22.       else  
  23.         throw ex;  // Any serious error occurr  
  24.     }  
  25.   } while (received < size);  

Call the Receive method using code such this:
  1. Socket socket = tcpClient.Client;  
  2. byte[] buffer = new byte[12];  // Length of the text "Hello world!"  
  3. try  
  4. // Receive data with timeout 10s  
  5.   MyClass.Receive(socket, buffer, 0, buffer.Length, 10000);  
  6.   string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);  
  7. }  
  8. catch (Exception ex) { /* ... */ }  
Ebook Download
View all
Learn
View all