Send and receive using sockets

walden systems, c#, sockets, socket.send, socket.receive, wordblock, tcpclient
C# is an elegant and type-safe object-oriented language that enables developers to build a variety of secure and robust applications that run on the .NET Framework. You can use C# to create Windows client applications, XML Web services, distributed components, client-server applications, database applications, and much, much more. Visual C# provides an advanced code editor, convenient user interface designers, integrated debugger, and many other tools to make it easier to develop applications based on the C# language and the .NET Framework.

This example 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 sends data from your buffer to a connected Socket. When you call the Send method it returns number of bytes which were sent. That doesn't mean that the bytes were already received by the other side, only that the data was stored in a socket buffer and the socket will try to send them. If the socket buffer is full a WouldBlock error occurs. 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 time)
{
   int startCount = Environment.TickCount;
   int sent = 0; // how many bytes is already sent
   do {
     if (Environment.TickCount > startCount + time)
       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; // serious error
     }
   } while (sent < size);
}


To call the Send method use following code. The TCP/IP socket is obtaind using TcpClient class. Use TcpClient.Client property to get the Socket.

Socket socket = tcpClient.Client;
string str = "Hello there";
try
{ // sends the text with timeout 20s
   MyClass.Send(socket, Encoding.UTF8.GetBytes(str), 0, str.Length, 20000);
}
catch (Exception ex)
{ /* ... */ }

Socket.Receive receives data from the socket to your buffer. The method returns number of received bytes. If the socket buffer is empty a WouldBlock error occurs. Following method tries to receive size bytes into the buffer to the offset position. If the operation lasts more than timeout, it throws an exception.

public static void Receive(Socket socket, byte[] buffer, int offset, int size, int time)
{
   int startCount = Environment.TickCount;
   int received = 0; // how many bytes is already received
   do {
     if (Environment.TickCount > startCount + time)
       throw new Exception("Timeout.");
     try {
       received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
     }
     catch (SocketException ex)
     {
       if (ex.SocketErrorCode == SocketError.WouldBlock ||
         ex.SocketErrorCode == SocketError.IOPending ||
         ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
       {
         // socket buffer is probably empty, wait and try again
         Thread.Sleep(30);
       }
       else
         throw ex; // error
     }
   } while (received < size);
}

To call the receive method, use the following code :

Socket socket = tcpClient.Client;
byte[] buffer = new byte[10]; // length of the text "Hello there"
try
{ // receive data with timeout 20s
   MyClass.Receive(socket, buffer, 0, buffer.Length, 20000);
   string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
}
catch (Exception ex)
{
   /* ... */
}