vthokie4ever
2009-09-11 22:50:37 UTC
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace SimpleConsoleServer
{
class Program
{
// Global methods
private static TcpListener tcpListener;
private static Thread listenThread;
private string endl = "\r\n";
///
/// Main server method
///
static void Main(string[] args)
{
tcpListener = new TcpListener(IPAddress.Any, 80);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
///
/// Listens for client connections
///
private static void ListenForClients()
{
tcpListener.Start();
while (true)
{
try
{
// Blocks until a client has connected to the server
TcpClient client = tcpListener.AcceptTcpClient();
// Create a thread to handle communication
// with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
catch (Exception)
{
}
}
}
///
/// Handles client connections
///
///
private static void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
do
{
bytesRead = 0;
try
{
// Blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception)
{
// A socket error has occured
break;
}
if (bytesRead == 0)
{
// The client has disconnected from the server
break;
}
// Message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
// Output message
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
} while (clientStream.DataAvailable);
// Release connections
clientStream.Close();
tcpClient.Close();
}
}
}