Created
March 3, 2018 01:10
-
-
Save yutopio/c0ad851cc82b51182a35d50909b76e3d to your computer and use it in GitHub Desktop.
Example of simple HTTP client / server by using Socket
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
using System; | |
using System.Net; | |
using System.Net.Sockets; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var s = new Socket( | |
AddressFamily.InterNetwork, | |
SocketType.Stream, | |
ProtocolType.Tcp | |
); | |
var ip = Dns.Resolve("google.com").AddressList[0]; | |
s.Connect(new IPEndPoint(ip, 80)); | |
var req = | |
$@"GET / HTTP/1.0 | |
Host: google.com | |
"; | |
var buffer = System.Text.Encoding.ASCII.GetBytes(req); | |
s.Send(buffer, 0, buffer.Length, SocketFlags.None); | |
buffer = new byte[1024 * 4]; | |
s.Receive(buffer, 0, buffer.Length, SocketFlags.None); | |
s.Shutdown(SocketShutdown.Receive); | |
s.Close(); | |
var txt = System.Text.Encoding.ASCII.GetString(buffer); | |
Console.WriteLine(txt); | |
} | |
static void Main2(string[] args) | |
{ | |
var s = new Socket( | |
AddressFamily.InterNetwork, | |
SocketType.Stream, | |
ProtocolType.Tcp | |
); | |
s.Bind(new IPEndPoint( | |
IPAddress.Parse("127.0.0.1"), 8080)); | |
s.Listen(10); | |
var i = 0; | |
while (true) | |
{ | |
i++; | |
var client = s.Accept(); | |
var buffer = new byte[1024 * 4]; | |
client.Receive(buffer, 0, buffer.Length, SocketFlags.None); | |
var response = | |
$@"HTTP/1.0 200 OK | |
Content-Type: text/ascii | |
Content-Length: 17 | |
Hello world! {i:0000}"; | |
buffer = System.Text.Encoding.ASCII.GetBytes(response); | |
client.Send(buffer, 0, buffer.Length, SocketFlags.None); | |
client.Shutdown(SocketShutdown.Send); | |
client.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment