title: Sockets in C#: How to get the response stream?
body: <p>I'm trying to replace this:</p>
  
  <pre><code>void ProcessRequest(object listenerContext)
  {
      var context = (HttpListenerContext)listenerContext;
      Uri URL = new Uri(context.Request.RawUrl);
      HttpWebRequest.DefaultWebProxy = null;
      HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
      httpWebRequest.Method = context.Request.HttpMethod;
      httpWebRequest.Headers.Clear();
      if (context.Request.UserAgent != null) httpWebRequest.UserAgent = context.Request.UserAgent;
      foreach (string headerKey in context.Request.Headers.AllKeys)
      {
          try { httpWebRequest.Headers.Set(headerKey, context.Request.Headers[headerKey]); }
              catch (Exception) { }
      }
  
      using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
      {
          Stream responseStream = httpWebResponse.GetResponseStream();
          if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
              responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
          else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                  responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
  
          MemoryStream memStream = new MemoryStream();
  
          byte[] respBuffer = new byte[4096];
          try
          {
              int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
              while (bytesRead &gt; 0)
              {
                  memStream.Write(respBuffer, 0, bytesRead);
                  bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
              }
          }
          finally
          {
              responseStream.Close();
          }
  
          byte[] msg = memStream.ToArray();
  
          context.Response.ContentLength64 = msg.Length;
          using (Stream strOut = context.Response.OutputStream)
          {
              strOut.Write(msg, 0, msg.Length);
          }
      }
      catch (Exception ex)
      {
          // Some error handling
      }
  }
  </code></pre>
  
  <p>with sockets. This is what I have so far:</p>
  
  <pre><code>void ProcessRequest(object listenerContext)
  {
      HttpListenerContext context = (HttpListenerContext)listenerContext;
      Uri URL = new Uri(context.Request.RawUrl);
      string getString = string.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\nAccept-Encoding: gzip\r\n\r\n",
                  context.Request.Url.PathAndQuery,
                  context.Request.UserHostName);
  
      Socket socket = null;
  
      string[] hostAndPort;
      if (context.Request.UserHostName.Contains(":"))
      {
          hostAndPort = context.Request.UserHostName.Split(':');
      }
      else
      {
          hostAndPort = new string[] { context.Request.UserHostName, "80" };
      }
  
      IPHostEntry ipAddress = Dns.GetHostEntry(hostAndPort[0]);
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddress.AddressList[0].ToString()), int.Parse(hostAndPort[1]));
      socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
      socket.Connect(ip);
  </code></pre>
  
  <p><strong>BEGIN NEW CODE</strong></p>
  
  <pre><code>Encoding ASCII = Encoding.ASCII;
  Byte[] byteGetString = ASCII.GetBytes(getString);
  Byte[] receiveByte = new Byte[256];
  string response = string.Empty;
  socket.Send(byteGetString, byteGetString.Length, 0);
  Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
  response += ASCII.GetString(receiveByte, 0, bytes);
  while (bytes &gt; 0)
  {
  bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
  strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);
  }
  socket.Close();
  
  string separator = "\r\n\r\n";
  string header = strPage.Substring(0,strPage.IndexOf(separator));
  string content = strPage.Remove(0, strPage.IndexOf(separator) + 4);
  
  byte[] byteResponse = ASCII.GetBytes(content);
  context.Response.ContentLength64 = byteResponse .Length;
  context.Response.OutputStream.Write(byteResponse , 0, byteResponse .Length);
  context.Response.OutputStream.Close();
  </code></pre>
  
  <p><strong>END NEW CODE</strong></p>
  
  <p>After connecting to the socket I don't know how to get the Stream response to decompress, and send back to <strong>context.Response.OutputStream</strong></p>
  
  <p>Any help will be appreciated.
  Thanks.
  Cheers.</p>
  
  <p><strong>EDIT 2:</strong>
  With this edit now seems to be working fine (same as HttpWebRequest at least). Do you find any error here?</p>
  
  <p><strong>EDIT 3:</strong>
  False alarm... Still can't get this working</p>
  
  <p><strong>EDIT 4:</strong>
  I needed to add the following lines to Scott's code ... because not always the first to bytes of reponseStream are the gzip magic number.
  The sequence seems to be: 0x0a (10), 0x1f (31), 0x8b (139). The last two are the gzip magic number. The first number was always before in my tests.</p>
  
  <pre><code>if (contentEncoding.Equals("gzip"))
  {
      int magicNumber = 0;
      while (magicNumber != 10)
          magicNumber = responseStream.ReadByte();
      responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
  }
  </code></pre>