szymski

Very simple Http server

Mar 8th, 2016
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.12 KB | None | 0 0
  1. import std.stdio, std.socket, core.thread;
  2.  
  3. class HttpClientThread : Thread {
  4.  
  5.     Socket client;
  6.  
  7.     this(Socket clientSocket) {
  8.         super(&Func);
  9.         client = clientSocket;
  10.     }
  11.  
  12.     string receiveString() {
  13.         string str = "";
  14.  
  15.         while(str.length < 5 || str[$ - 4 .. $] != "\r\n\r\n") {
  16.             char[1] c = void;
  17.             client.receive(c);
  18.             str ~= c;
  19.         }
  20.  
  21.         return str;
  22.     }
  23.  
  24.     void Func() {
  25.         writeln("Connection accepted from ", client.remoteAddress);
  26.  
  27.         string request = receiveString();
  28.         writeln("Request: ", request);
  29.  
  30.         client.send(`HTTP/1.1 300 OK
  31. Content-Type: text/html; charset=UTF-8
  32.  
  33. <b>OMG!</b> this shit works O_o
  34.  
  35.         `);
  36.  
  37.         client.close();
  38.     }
  39. }
  40.  
  41. class HttpServer {
  42.  
  43.     TcpSocket tcpSocket;
  44.  
  45.     ~this() {
  46.         if(tcpSocket.isAlive)
  47.             tcpSocket.close();
  48.     }
  49.  
  50.     void Start(string ip, ushort port) {
  51.         tcpSocket = new TcpSocket();
  52.         tcpSocket.bind(parseAddress(ip, port));
  53.         tcpSocket.listen(0);
  54.         writeln("Listening on ", ip, ":", port);
  55.  
  56.         while(true) {
  57.             new HttpClientThread(tcpSocket.accept()).start();
  58.         }
  59.     }
  60.  
  61. }
  62.  
  63. void main()
  64. {
  65.     auto http = new HttpServer();
  66.     http.Start("192.168.1.101", 8888);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment