Advertisement
Guest User

HTTPS via TcpClient

a guest
Jun 29th, 2010
1,368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 6.36 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Security;
  6. using System.Net.Sockets;
  7. using System.Security.Authentication;
  8. using System.Text;
  9. using System.Threading;
  10.  
  11. namespace DeriveClassNameSpace.Services.Web
  12. {
  13.     public class TcpMessaging
  14.     {
  15.         public const int HttpCodepage = 28591;
  16.         public static readonly Encoding HttpEncoding = Encoding.GetEncoding( HttpCodepage );
  17.         private static readonly string divider = new string( '-', 20 );
  18.         private static readonly string simpleGet =
  19. @"GET / HTTP/1.0
  20. Host: {0}
  21. Content-Length: -1
  22. Connection: Keep-Alive
  23. Authorization: Basic {1}
  24.  
  25. ";
  26.  
  27.         public static void TestViaTcp( IPEndPoint endpoint, string auth, bool useSSL )
  28.         {
  29.             if (endpoint != null)
  30.             {
  31.                 Console.WriteLine( "Connecting..." );
  32.                 using (TcpClient request = new TcpClient())
  33.                 {
  34.                     request.Connect( endpoint );
  35.                     Console.WriteLine( String.Format( "Connection made from {0} to {1}", request.Client.LocalEndPoint, endpoint ) );
  36.                     using (NetworkStream tcpStream = request.GetStream())
  37.                     {
  38.                         TcpMessageState state = null;
  39.                         try
  40.                         {
  41.                             string host = endpoint.Address.ToString();
  42.                             if (useSSL)
  43.                             {
  44.                                 RemoteCertificateValidationCallback callback =
  45.                                     new RemoteCertificateValidationCallback( Program.ValidateServerCertificate );
  46.                                 SslProtocols protocol = SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls;
  47.                                 using (SslStream secureStream = new SslStream( tcpStream, false, callback ))
  48.                                 {
  49.                                     secureStream.AuthenticateAsClient( endpoint.ToString(), null, protocol, false );
  50.                                     RequestResponse( secureStream, host, auth, ref state );
  51.                                 }
  52.                             }
  53.                             else
  54.                             {
  55.                                 RequestResponse( tcpStream, host, auth, ref state );
  56.                             }
  57.                         }
  58.                         catch (Exception e)
  59.                         {
  60.                             Console.WriteLine( "ERROR DURING GET:  {0}", e.Message );
  61.                         }
  62.                         finally
  63.                         {
  64.                             if (state != null)
  65.                             {
  66.                                 state.Close();
  67.                                 state = null;
  68.                             }
  69.                         }
  70.  
  71.                         if (tcpStream != null)
  72.                         {
  73.                             tcpStream.Close();
  74.                         }
  75.                     }
  76.  
  77.                     if (request != null)
  78.                     {
  79.                         request.Close();
  80.                     }
  81.                 }
  82.             }
  83.         }
  84.  
  85.         private static void RequestResponse( Stream stream, string host, string auth, ref TcpMessageState state )
  86.         {
  87.             string tcpMsg = String.Format( simpleGet, host, auth );
  88.             byte[] rawMsg = HttpEncoding.GetBytes( tcpMsg );
  89.             Console.WriteLine( "Sending message..." );
  90.             stream.Write( rawMsg, 0, rawMsg.Length );
  91.             stream.Flush();
  92.  
  93.             state = new TcpMessageState( stream, HttpEncoding );
  94.             Console.WriteLine( "Waiting for response..." );
  95.             IAsyncResult result = state.Stream.BeginRead( state.Buffer, 0, TcpMessageState.BufferSize, new AsyncCallback( ReceiveCallback ), state );
  96.             state.ResponseReceived.WaitOne();
  97.  
  98.             Console.WriteLine( "Response received:" );
  99.             Console.WriteLine( divider );
  100.             string response = state.Message;
  101.  
  102.             // Look for the header/body seperator, two 'newline' characters (which are platform dependant)
  103.             int pos1 = response.IndexOf( "\r\n\r\n" );
  104.             int pos2 = response.IndexOf( "\n\n" );
  105.             if (pos1 < 1 && pos2 > 1)
  106.             {
  107.                 pos2 += 2;
  108.                 pos1 = pos2;
  109.             }
  110.             else if (pos2 < 1 && pos1 > 1)
  111.             {
  112.                 pos1 += 4;
  113.                 pos2 = pos1;
  114.             }
  115.             else
  116.             {
  117.                 pos1 += 4;
  118.                 pos2 += 2;
  119.             }
  120.  
  121.             int pos = Math.Min( pos1, pos2 );
  122.             if (response.Length > 1024 && pos > 0)
  123.             {
  124.                 // Replace the body, I'm only interested in the headers at this point
  125.                 response = response.Substring( 0, pos ) + String.Format( "<body of {0} characters removed>", response.Length - pos );
  126.             }
  127.  
  128.             Console.WriteLine( response );
  129.             Console.WriteLine( divider );
  130.         }
  131.  
  132.         private static void ReceiveCallback( IAsyncResult ar )
  133.         {
  134.             try
  135.             {
  136.                 TcpMessageState state = ar.AsyncState as TcpMessageState;
  137.                 if (state == null)
  138.                 {
  139.                     Debug.WriteLine( String.Format( "Did not recieve expected state object! Wanted: {0}, Got: {1}", typeof( TcpMessageState ), ar.AsyncState == null ? "null" : ar.AsyncState.GetType().ToString() ) );
  140.                 }
  141.  
  142.                 // Read data from the remote device.
  143.                 int bytesRead = state.Stream.EndRead( ar );
  144.                 if (bytesRead > 0)
  145.                 {
  146.                     // There might be more data, so store the data received so far.
  147.                     state.AddBufferToMessage( bytesRead );
  148.  
  149.                     // Get the rest of the data.
  150.                     state.Stream.BeginRead( state.Buffer, 0, TcpMessageState.BufferSize, new AsyncCallback( ReceiveCallback ), state );
  151.                 }
  152.                 else
  153.                 {
  154.                     // Signal that all bytes have been sent.
  155.                     state.ResponseReceived.Set();
  156.                 }
  157.             }
  158.             catch (Exception e)
  159.             {
  160.                 Debug.WriteLine( "ERROR: " + e.Message );
  161.             }
  162.         }
  163.  
  164.         private void UnreadMessage( TcpClient request )
  165.         {
  166.             // Data to read?
  167.             if (request.Connected && request.Available > 0)
  168.             {
  169.                 Console.WriteLine( "TcpClient has a message for us!" );
  170.                 Console.WriteLine( divider );
  171.                 NetworkStream tcpStream = request.GetStream();
  172.                 TcpMessageState state = new TcpMessageState( tcpStream, HttpEncoding );
  173.                 int count = tcpStream.Read( state.Buffer, 0, request.Available );
  174.                 state.AddBufferToMessage( count );
  175.                 Console.WriteLine( String.Format( "Read {0} bytes: {1}", count, state.Message ) );
  176.                 Console.WriteLine( divider );
  177.             }
  178.         }
  179.  
  180.         private class TcpMessageState
  181.         {
  182.             internal const int BufferSize = 2 ^ 11;
  183.             private StringBuilder message = new StringBuilder();
  184.  
  185.             internal TcpMessageState( Stream stream, Encoding encoding )
  186.             {
  187.                 this.ResponseReceived = new AutoResetEvent( false );
  188.                 this.Encoding = encoding;
  189.                 this.Stream = stream;
  190.                 this.Buffer = new byte[BufferSize];
  191.             }
  192.  
  193.             public AutoResetEvent ResponseReceived
  194.             {
  195.                 get;
  196.                 private set;
  197.             }
  198.  
  199.             public string Message
  200.             {
  201.                 get
  202.                 {
  203.                     return this.message.ToString();
  204.                 }
  205.             }
  206.  
  207.             public Encoding Encoding
  208.             {
  209.                 get;
  210.                 private set;
  211.             }
  212.  
  213.             public Stream Stream
  214.             {
  215.                 get;
  216.                 private set;
  217.             }
  218.  
  219.             public byte[] Buffer
  220.             {
  221.                 get;
  222.                 private set;
  223.             }
  224.  
  225.             internal void AddBufferToMessage( int bytesRead )
  226.             {
  227.                 this.message.Append( this.Encoding.GetString( this.Buffer, 0, bytesRead ) );
  228.             }
  229.  
  230.             internal void Close()
  231.             {
  232.                 this.Buffer = null;
  233.                 this.Encoding = null;
  234.                 this.ResponseReceived.Close();
  235.                 this.ResponseReceived = null;
  236.                 this.Stream.Close();
  237.                 this.Stream = null;
  238.             }
  239.         }
  240.     }
  241. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement