From bedea1ec313b44cd056fe0de0f9d060ef94e8c9e Mon Sep 17 00:00:00 2001 From: "Adam D. Ruppe" Date: Sun, 5 Feb 2012 19:56:53 -0500 Subject: [PATCH] basic threading --- httpd.d | 21 ++++++++++++--------- netman.d | 41 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 14 deletions(-) diff --git a/httpd.d b/httpd.d index 37dbb06..e5cd570 100644 --- a/httpd.d +++ b/httpd.d @@ -89,29 +89,32 @@ class HttpdConnection(CustomCgi) : Connection /* if(is(CustomCgi : Cgi)) */ { Cgi cgi; try { - cgi = new CustomCgi(headers, data, peerAddress(), - cast(void delegate(const(ubyte)[])) &this.write); + cgi = new CustomCgi(headers, data, peerAddress(), + cast(void delegate(const(ubyte)[])) &this.write); } catch(Throwable t) { write("HTTP/1.1 400 Bad Request\r\n"); write("Content-Type: text/plain\r\n"); + string s = t.toString(); + write("Content-Length: "~to!string(s.length)~"\r\n"); write("Connection: close\r\n"); write("\r\n"); - write(t.toString()); + write(s); + + closeConnection = true; return; } - try { - handler(cgi); + scope(exit) { cgi.close(); cgi.dispose(); + } + + try { + handler(cgi); } catch(Throwable e) { cgi.setResponseStatus("500 Internal Server Error"); cgi.write(e.toString()); - cgi.close(); - cgi.dispose(); - - return; } } diff --git a/netman.d b/netman.d index 97821bf..9b06f5a 100644 --- a/netman.d +++ b/netman.d @@ -54,7 +54,7 @@ class ConnectionException : Exception { class NetworkManager { // you might want to override this to construct subclasses of connection protected: - Connection allocConnection(int port){ + Connection allocConnection(int port) { if(auto a = port in allocs) return (*a)(); assert(0); @@ -266,10 +266,19 @@ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, on.sizeof); if(s == -1) throw new Exception("accept"); - auto con = allocConnection(c.port); - con.parentManager = this; - addConnection(con, s, addr, c.port); - con.onRemoteConnect(); + version(threaded_connections) { + auto con = allocConnection(c.port); + con.socket = s; + con.addr = addr; + con.port = c.port; + auto t = new ConnectionThread(con); + t.start(); + } else { + auto con = allocConnection(c.port); + con.parentManager = this; + addConnection(con, s, addr, c.port); + con.onRemoteConnect(); + } } } @@ -476,3 +485,25 @@ int now() { return cast(int) getUTCtime(); } + + +version(threaded_connections) { + import core.thread; + import std.stdio : writeln; + class ConnectionThread : Thread { + Connection connection; + this(Connection c) { + connection = c; + super(&run); + } + + void run() { + scope(exit) + connection.disconnectNow(); + auto manager = new NetworkManager(); + connection.parentManager = manager; + manager.addConnection(connection, connection.socket, connection.addr, connection.port); + while(manager.proceed()) {} + } + } +}