I'm trying to learn how to use Sockets to make web requests, but I'm struggling to find anything online. I've found lots of "client" -> "server" tutorials using sockets, but not开发者_JAVA百科hing that talks about making web requests, scrapers, etc.
I want to be able to develop multi threaded apps using sockets as I've heard they are much easier to work with.
I'm trying to learn how to use Sockets to make web requests, but I'm struggling to find anything online.
If by web requests you mean HTTP requests then using sockets would be too low level. I would recommend you using WebClient or a WebRequest for this purpose. For example here's how to send an HTTP request to google.com and fetch the resulting HTML:
using System;
using System.Net;
class Program
{
static void Main()
{
using (var client = new WebClient())
{
var result = client.DownloadString("http://www.google.com");
Console.WriteLine(result);
}
}
}
UPDATE:
As requested in the comments section here's an example for learning using sockets:
using System;
using System.IO;
using System.Net.Sockets;
class Program
{
static void Main()
{
using (var client = new TcpClient("www.google.com", 80))
using (var stream = client.GetStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
{
writer.Write(
@"GET / HTTP/1.1
Host: www.google.com
Connection: close
");
writer.Flush();
Console.WriteLine(reader.ReadToEnd());
}
}
}
Disclaimer: absolutely never write any code like this in any real application.
精彩评论