Avoid socket leaks in examples.

This commit is contained in:
Sönke Ludwig 2020-11-25 23:23:58 +01:00
parent 958856f6f1
commit a44d3f2655
2 changed files with 9 additions and 2 deletions

View file

@ -19,7 +19,7 @@ void main()
conn.readLine(r); conn.readLine(r);
if (!r.count) break; if (!r.count) break;
} }
conn.write(cast(const(ubyte)[])"HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/plain\r\nConnection: keep-alive\r\n\r\nHello, World!"); conn.write(cast(const(ubyte)[])"HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/plain\r\nConnection: keep-alive\r\nKeep-Alive: timeout=10\r\n\r\nHello, World!");
conn.flush(); conn.flush();
} }
} catch (Exception e) { } catch (Exception e) {
@ -30,6 +30,7 @@ void main()
auto listener = listenTCP(8080, &staticAnswer, "127.0.0.1"); auto listener = listenTCP(8080, &staticAnswer, "127.0.0.1");
logInfo("Listening to HTTP requests on http://127.0.0.1:8080/"); logInfo("Listening to HTTP requests on http://127.0.0.1:8080/");
scope (exit) listener.stopListening();
runApplication(); runApplication();
} }

View file

@ -5,10 +5,16 @@ import vibe.core.stream : pipe;
void main() void main()
{ {
listenTCP(7000, (conn) @safe nothrow { auto listeners = listenTCP(7000, (conn) @safe nothrow {
try pipe(conn, conn); try pipe(conn, conn);
catch (Exception e) catch (Exception e)
logError("Error: %s", e.msg); logError("Error: %s", e.msg);
}); });
// closes the listening sockets
scope (exit)
foreach (l; listeners)
l.stopListening();
runApplication(); runApplication();
} }