1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
namespace webServer
{
class HTTPServer
{
public void start()
{
Socket CurrentClient = null;
Socket ServerSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
ServerSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000));
ServerSocket.Listen(10);
while (true)
{
int[] sizeReqCli = { 0 };
String reqCli = null;
String fileName = null;
CurrentClient = ServerSocket.Accept();
reqCli = this.receiveMsg(1024, CurrentClient,sizeReqCli);
fileName = this.getNombrePagina(reqCli);
sendMsg("HTTP/1.0 200 OK", CurrentClient);
sendMsg("Content-Type : text/HTML", CurrentClient);
sendMsg("", CurrentClient);
try
{
using (StreamReader sr = new StreamReader(fileName))
{
String line;
while ((line = sr.ReadLine()) != null)
{
int dtSent;
dtSent = sendMsg(line, CurrentClient);
}
}
}
catch (FileNotFoundException e)
{
Console.WriteLine("File not found");
Console.WriteLine(e.Message);
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
catch (SocketException E)
{
Console.WriteLine(E.Message);
}
}
private int sendMsg(String msg, Socket sock)
{
int dtSent = sock.Send(System.Text.Encoding.UTF8.GetBytes(msg), msg.Length, SocketFlags.None);
if (dtSent == 0)
{
Console.WriteLine("Aucune donnée n'a été envoyée");
}
return dtSent;
}
private String receiveMsg(int sizeMsg, Socket sock, int[] msgSize)
{
byte[] msg = new byte[sizeMsg];
int dtRcv = sock.Receive(msg, msg.Length, SocketFlags.None);
msgSize[0] = dtRcv;
if (dtRcv == 0)
{
Console.WriteLine("Rien reçu");
return null;
}
return System.Text.Encoding.UTF8.GetString(msg);
}
private String getNombrePagina (String reqCli)
{
int ind = reqCli.IndexOf("GET");
if (ind == -1)
{
Console.WriteLine("Methode pas implementée");
return null;
}
Regex regEmail = new Regex(@"^GET /([a-zA-Z0-9.]+) HTTP/1.1");
Match monMatch = regEmail.Match(reqCli);
if (monMatch.Success)
return monMatch.Groups[1].Value;
else
Console.WriteLine("Regexp mauvaise");
return null;
}
}
class MainClass
{
static void Main(string[] args)
{
HTTPServer startIt = new HTTPServer();
startIt.start();
}
}
} |
Partager