Created
February 15, 2013 22:21
-
-
Save yetanotherchris/4964062 to your computer and use it in GitHub Desktop.
NetworkStream example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string host = "google.com"; | |
string page = "/search?q=networkstream"; | |
// This is the simplest way of getting a NetworkStream back. It can also be | |
// done at a lower level using your own Socket class and the options you | |
// require. | |
TcpClient tcp = new TcpClient(); | |
tcp.Connect(host, 80); | |
NetworkStream stream = tcp.GetStream(); | |
// Send a HTTP request | |
byte[] data = Encoding.Unicode.GetBytes(string.Format("GET {0} HTTP/1.0{1}{1}", page, "\r\n")); | |
stream.Write(data, 0, data.Length); | |
// Get the returned data in 1k chunks. | |
byte[] buffer = new byte[1024]; | |
int i = stream.Read(buffer, 0, 1024); | |
StringBuilder builder = new StringBuilder(); | |
while (i > 0) | |
{ | |
builder.Append(Encoding.Unicode.GetString(buffer)); | |
i = stream.Read(buffer, 0, 1024); | |
} | |
// Write out to a file. NB the server header will be contained in this file too. | |
using (StreamWriter writer = new StreamWriter(@"c:\out.html")) | |
writer.Write(builder.ToString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment