Skip to content

Instantly share code, notes, and snippets.

@pahaz
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pahaz/5e3c45fa06d6a4e754f2 to your computer and use it in GitHub Desktop.
Save pahaz/5e3c45fa06d6a4e754f2 to your computer and use it in GitHub Desktop.
Simple HTTP Server
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class HTTPServer
{
public static void Main()
{
Console.Title = "Simple HTTP server";
int port = 8080;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.Write("Connected! ");
Console.Write(client.Client.RemoteEndPoint.ToString());
Console.Write(" -> ");
Console.WriteLine(client.Client.LocalEndPoint.ToString());
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
byte[] in_buffer = new Byte[1024*4];
string in_buffer_string = "";
i = stream.Read(in_buffer, 0, in_buffer.Length);
Console.Write("Read ");
Console.Write(i);
Console.WriteLine(" bytes");
in_buffer_string += System.Text.Encoding.ASCII.GetString(in_buffer, 0, i);
Console.Write("Received: ");
Console.WriteLine(in_buffer_string);
string out_html = "<!DOCTYPE html>\n<h1>Hi!</h1>";
byte[] out_buffer = makeResponce(out_html);
// Send back a response.
stream.Write(out_buffer, 0, out_buffer.Length);
Console.Write("Sent: ");
Console.WriteLine(out_buffer);
// Shutdown and end connection
client.Close();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
static byte[] makeResponce(string html)
{
byte[] b_html = System.Text.Encoding.UTF8.GetBytes(html);
String header = "HTTP/1.1 200 OK\r\n";
header += "Server: SuperSimpleServer v0.1\r\n";
header += "Content-Type: text/html; charset=utf-8\r\n";
header += "Content-Length: " + b_html.Length + "\r\n\r\n";
byte[] b_header = System.Text.Encoding.UTF8.GetBytes(header);
byte[] b_response = new byte[b_html.Length + b_header.Length];
Array.Copy(b_header, 0, b_response, 0, b_header.Length);
Array.Copy(b_html, 0, b_response, b_header.Length, b_html.Length);
return b_response;
}
}
@DimaDmiTreX
Copy link

Да

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment