All pastes #406262 Raw Edit

Unnamed

public text v1 · immutable
·published 2007-03-22 08:17 UTC
rendered paste body
using System;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Collections;

namespace GrabPageServer
{
	class GrabPageServer
	{
		static void Send(string message, NetworkStream socketStream)
		{
			char[] theMessage;
			theMessage = message.ToCharArray();
			for ( int i = 0; i < theMessage.Length; i++ ) socketStream.WriteByte( (byte) theMessage[i] );
		}

		static void Main()
		{
			int port = 80;
//			BinaryWriter writer = null;
//			BinaryReader reader = null;
			ArrayList theRequest = new ArrayList();
			string tehRequest = "";

			// wait for a client connection and display the text the client sends
			try
			{                               
				// create TcpListener
				TcpListener server = null;
				server = new TcpListener( port );
                                
				// start TcpListener to wait for the next connection request
				server.Start();

				Console.WriteLine("Waiting for connection...\r\n");

				// establish connection upon client request
				while ( true )
				{
					// accept an incoming connection
					Socket connection = null;
					connection = server.AcceptSocket();
                
					// create NetworkStream object associated with socket
					NetworkStream socketStream = null;
					socketStream = new NetworkStream( connection );

					// chain it to BinaryWriter and BinaryReader
//					writer = new BinaryWriter( socketStream );
//					reader = new BinaryReader( socketStream );

					// get client's IP address and port
					IPEndPoint ipend = (IPEndPoint) connection.RemoteEndPoint;
					
					// read the HTTP request from the client
					int c = 0;
//					int d = 0;
//					while (d != ((int) '\r' + (int) '\n'))
					while (connection.Available > 0)
					{
//						d = c;
						c = socketStream.ReadByte();
//						if (c == '\r') d += c;
						theRequest.Add((char) c);
					}
					foreach (char message in theRequest) tehRequest += message;
					theRequest.Clear();

					// show where the client is from and the HTTP request
					Console.WriteLine( "Connection from " + ipend.Address + " via its port " + ipend.Port + " with the following request: ");
					Console.Write( tehRequest );
					tehRequest = "";

					// send the greeting message to the client
					Send("HTTP/1.1 200 OK\r\n", socketStream);
					Send("Date: " + System.DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT\r\n", socketStream);
					Send("Server: CrazyHTTP/1.0\r\n", socketStream);
					Send("Connection: close\r\n", socketStream);
					Send("Content-Type: text/html\r\n\r\n", socketStream);
					Send("<html><h1>Greetings from the Server!</h1></html>\r\n", socketStream);

					// close the connection
					socketStream.Close();
					connection.Close();
				}
			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
			}
		}
	}
}