Socket Send and Receive [C#]


SUBMITTED BY: menamagice

DATE: Aug. 9, 2017, 1:51 a.m.

FORMAT: ANTLR With C# Target

SIZE: 3.7 kB

HITS: 191

  1. 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.
  2. Socket.Send method
  3. 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.
  4. 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.
  5. [C#]
  6. public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
  7. {
  8. int startTickCount = Environment.TickCount;
  9. int sent = 0; // how many bytes is already sent
  10. do {
  11. if (Environment.TickCount > startTickCount + timeout)
  12. throw new Exception("Timeout.");
  13. try {
  14. sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
  15. }
  16. catch (SocketException ex)
  17. {
  18. if (ex.SocketErrorCode == SocketError.WouldBlock ||
  19. ex.SocketErrorCode == SocketError.IOPending ||
  20. ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  21. {
  22. // socket buffer is probably full, wait and try again
  23. Thread.Sleep(30);
  24. }
  25. else
  26. throw ex; // any serious error occurr
  27. }
  28. } while (sent < size);
  29. }
  30. 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).
  31. [C#]
  32. Socket socket = tcpClient.Client;
  33. string str = "Hello world!";
  34. try
  35. { // sends the text with timeout 10s
  36. MyClass.Send(socket, Encoding.UTF8.GetBytes(str), 0, str.Length, 10000);
  37. }
  38. catch (Exception ex) { /* ... */ }
  39. Socket.Receive method
  40. 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.
  41. 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.
  42. [C#]
  43. public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
  44. {
  45. int startTickCount = Environment.TickCount;
  46. int received = 0; // how many bytes is already received
  47. do {
  48. if (Environment.TickCount > startTickCount + timeout)
  49. throw new Exception("Timeout.");
  50. try {
  51. received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
  52. }
  53. catch (SocketException ex)
  54. {
  55. if (ex.SocketErrorCode == SocketError.WouldBlock ||
  56. ex.SocketErrorCode == SocketError.IOPending ||
  57. ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
  58. {
  59. // socket buffer is probably empty, wait and try again
  60. Thread.Sleep(30);
  61. }
  62. else
  63. throw ex; // any serious error occurr
  64. }
  65. } while (received < size);
  66. }
  67. Call the Receive method using code such this:
  68. [C#]
  69. Socket socket = tcpClient.Client;
  70. byte[] buffer = new byte[12]; // length of the text "Hello world!"
  71. try
  72. { // receive data with timeout 10s
  73. MyClass.Receive(socket, buffer, 0, buffer.Length, 10000);
  74. string str = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
  75. }
  76. catch (Exception ex) { /* ... */ }

comments powered by Disqus