Connect To Web Server Using TcpClient In C#

This snippet connects to a web server and requests for a page. It uses the TcpClient to send header information to the server.


  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.IO;
  5. class Program
  6. {
  7.     static void Main(string[] args)
  8.     {
  9.         string host = "";
  10.         string file = "";
  11.         try
  12.         {
  13.             TcpClient tcpClient = new TcpClient(host, 80);
  14.             NetworkStream nStream = tcpClient.GetStream();
  15.             StreamReader sReader = new StreamReader(nStream);
  16.             StreamWriter sWriter = new StreamWriter(nStream);
  17.             sWriter.WriteLine("GET /" + file + " HTTP/1.1");
  18.             sWriter.WriteLine("Host: " + host);
  19.             sWriter.WriteLine("");
  20.             sWriter.Flush();
  21.             String response = "";
  22.             while ((response = sReader.ReadLine()) != null)
  23.             {
  24.                 Console.WriteLine(sReader.ReadLine());
  25.             }
  26.         }
  27.         catch (Exception e)
  28.         {
  29.             Console.WriteLine(e.Message);
  30.         }
  31.         Console.ReadKey();
  32.     }
  33. }

No comments:

Post a Comment