Advertisement
Vadorequest

SocketClient

Sep 30th, 2013
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.63 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Net.Sockets;
  7. using System.Threading;
  8. using System.Net;
  9.  
  10. namespace SocketsTest
  11. {
  12.     class SocketClient
  13.     {
  14.         // Cached Socket object that will be used by each call for the lifetime of this class
  15.         Socket _socket = null;
  16.  
  17.         // Signaling object used to notify when an asynchronous operation is completed
  18.         static ManualResetEvent _clientDone = new ManualResetEvent(false);
  19.  
  20.         // Define a timeout in milliseconds for each asynchronous call. If a response is not received within this
  21.         // timeout period, the call is aborted.
  22.         const int TIMEOUT_MILLISECONDS = 5000;
  23.  
  24.         // The maximum size of the data buffer to use with the asynchronous socket methods
  25.         const int MAX_BUFFER_SIZE = 2048;
  26.  
  27.  
  28.         /// <summary>
  29.         /// Attempt a TCP socket connection to the given host over the given port
  30.         /// </summary>
  31.         /// <param name="hostName">The name of the host</param>
  32.         /// <param name="portNumber">The port number to connect</param>
  33.         /// <returns>A string representing the result of this connection attempt</returns>
  34.         public string Connect(string hostName, int portNumber)
  35.         {
  36.             string result = string.Empty;
  37.  
  38.             // Create DnsEndPoint. The hostName and port are passed in to this method.
  39.             DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
  40.  
  41.             // Create a stream-based, TCP socket using the InterNetwork Address Family.
  42.             _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  43.  
  44.             // Create a SocketAsyncEventArgs object to be used in the connection request
  45.             SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
  46.             socketEventArg.RemoteEndPoint = hostEntry;
  47.  
  48.             // Inline event handler for the Completed event.
  49.             // Note: This event handler was implemented inline in order to make this method self-contained.
  50.             socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
  51.             {
  52.                 // Retrieve the result of this request
  53.                 result = e.SocketError.ToString();
  54.  
  55.                 // Signal that the request is complete, unblocking the UI thread
  56.                 _clientDone.Set();
  57.             });
  58.  
  59.             // Sets the state of the event to nonsignaled, causing threads to block
  60.             _clientDone.Reset();
  61.  
  62.             // Make an asynchronous Connect request over the socket
  63.             _socket.ConnectAsync(socketEventArg);
  64.  
  65.             // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  66.             // If no response comes back within this time then proceed
  67.             _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  68.  
  69.             return result;
  70.         }
  71.  
  72.  
  73.         /// <summary>
  74.         /// Send the given data to the server using the established connection
  75.         /// </summary>
  76.         /// <param name="data">The data to send to the server</param>
  77.         /// <returns>The result of the Send request</returns>
  78.         public string Send(string data)
  79.         {
  80.             string response = "Operation Timeout";
  81.  
  82.             // We are re-using the _socket object initialized in the Connect method
  83.             if (_socket != null)
  84.             {
  85.                 // Create SocketAsyncEventArgs context object
  86.                 SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
  87.  
  88.                 // Set properties on context object
  89.                 socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
  90.                 socketEventArg.UserToken = null;
  91.  
  92.                 // Inline event handler for the Completed event.
  93.                 // Note: This event handler was implemented inline in order
  94.                 // to make this method self-contained.
  95.                 socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
  96.                 {
  97.                     response = e.SocketError.ToString();
  98.  
  99.                     // Unblock the UI thread
  100.                     _clientDone.Set();
  101.                 });
  102.  
  103.                 // Add the data to be sent into the buffer
  104.                 byte[] payload = Encoding.UTF8.GetBytes(data);
  105.                 socketEventArg.SetBuffer(payload, 0, payload.Length);
  106.  
  107.                 // Sets the state of the event to nonsignaled, causing threads to block
  108.                 _clientDone.Reset();
  109.  
  110.                 // Make an asynchronous Send request over the socket
  111.                 _socket.SendAsync(socketEventArg);
  112.  
  113.                 // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  114.                 // If no response comes back within this time then proceed
  115.                 _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  116.             }
  117.             else
  118.             {
  119.                 response = "Socket is not initialized";
  120.             }
  121.  
  122.             return response;
  123.         }
  124.  
  125.  
  126.         /// <summary>
  127.         /// Receive data from the server using the established socket connection
  128.         /// </summary>
  129.         /// <returns>The data received from the server</returns>
  130.         public string Receive()
  131.         {
  132.             string response = "Operation Timeout";
  133.  
  134.             // We are receiving over an established socket connection
  135.             if (_socket != null)
  136.             {
  137.                 // Create SocketAsyncEventArgs context object
  138.                 SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
  139.                 socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
  140.  
  141.                 // Setup the buffer to receive the data
  142.                 socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
  143.  
  144.                 // Inline event handler for the Completed event.
  145.                 // Note: This even handler was implemented inline in order to make
  146.                 // this method self-contained.
  147.                 socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
  148.                 {
  149.                     if (e.SocketError == SocketError.Success)
  150.                     {
  151.                         // Retrieve the data from the buffer
  152.                         response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
  153.                         response = response.Trim('\0');
  154.                     }
  155.                     else
  156.                     {
  157.                         response = e.SocketError.ToString();
  158.                     }
  159.  
  160.                     _clientDone.Set();
  161.                 });
  162.  
  163.                 // Sets the state of the event to nonsignaled, causing threads to block
  164.                 _clientDone.Reset();
  165.  
  166.                 // Make an asynchronous Receive request over the socket
  167.                 _socket.ReceiveAsync(socketEventArg);
  168.  
  169.                 // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
  170.                 // If no response comes back within this time then proceed
  171.                 _clientDone.WaitOne(TIMEOUT_MILLISECONDS);
  172.             }
  173.             else
  174.             {
  175.                 response = "Socket is not initialized";
  176.             }
  177.  
  178.             return response;
  179.         }
  180.  
  181.  
  182.  
  183.         /// <summary>
  184.         /// Closes the Socket connection and releases all associated resources
  185.         /// </summary>
  186.         public void Close()
  187.         {
  188.             if (_socket != null)
  189.             {
  190.                 _socket.Close();
  191.             }
  192.         }
  193.     }
  194. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement