Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sockets Help and Advice

Tags:

c#

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 nothing 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.

like image 600
Peppi Hasting Avatar asked Jul 07 '26 17:07

Peppi Hasting


1 Answers

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.

like image 187
Darin Dimitrov Avatar answered Jul 10 '26 08:07

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!