Skip to content

Instantly share code, notes, and snippets.

@msbukkuri
Created September 19, 2011 05:17
Show Gist options
  • Select an option

  • Save msbukkuri/1226010 to your computer and use it in GitHub Desktop.

Select an option

Save msbukkuri/1226010 to your computer and use it in GitHub Desktop.
C# - Web Server (Old Implementation)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MyFirstWebServer
{
public class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
public void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] message = new byte[tcpClient.ReceiveBufferSize];
int bytesRead;
string messageString = string.Empty;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, message.Length);
//if(bytesRead > 0)
// break;
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
}
//Console.WriteLine("Received from Client: " + encoder.GetString(message));
byte[] buffer = encoder.GetBytes("HTTP 1.1 200 OK");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
tcpClient.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment