app.d 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import std.stdio;
  2. import std.conv;
  3. import slf4d;
  4. import handy_httpd;
  5. import handy_httpd.components.websocket;
  6. import handy_httpd.handlers.path_handler;
  7. import handy_httpd.handlers.file_resolving_handler;
  8. class MyWebSocketHandler : WebSocketMessageHandler{
  9. override void onConnectionEstablished(WebSocketConnection conn, in HttpRequest request){
  10. infoF!"Connection established with id %s"(conn.id); // id 8a4429e7-19b8-4dc4-bca6-14f64a471392
  11. conn.sendTextMessage("Hey yourself!");
  12. }
  13. override void onTextMessage(WebSocketTextMessage msg){
  14. infoF!"Got TEXT: %s"(msg.payload);
  15. //msg.conn.sendTextMessage("Hey yourself!");
  16. msg.conn.sendTextMessage(msg.payload ~ " :)");
  17. }
  18. override void onCloseMessage(WebSocketCloseMessage msg){
  19. infoF!"Closed: %d, %s"(msg.statusCode, msg.message);
  20. }
  21. }
  22. void main(string[] args){
  23. ServerConfig cfg;
  24. if(args.length > 1){
  25. cfg.port = args[1].to!ushort;
  26. }
  27. cfg.workerPoolSize = 3;
  28. cfg.enableWebSockets = true; // Important! Websockets won't work unless `enableWebSockets` is set to true!
  29. WebSocketHandler handler = new WebSocketHandler(new MyWebSocketHandler());
  30. //new HttpServer(new FileResolvingHandler("public"), cfg).start();
  31. PathHandler pathHandler = new PathHandler()
  32. .addMapping(Method.GET, "/ws", handler)
  33. .addMapping("/**", new FileResolvingHandler("public"));
  34. new HttpServer(pathHandler, cfg).start();
  35. }