Browse Source

ws example

221V 2 weeks ago
parent
commit
3ad8b0bcf1
2 changed files with 35 additions and 3 deletions
  1. 1 1
      README.md
  2. 34 2
      htest/source/app.d

+ 1 - 1
README.md

@@ -9,7 +9,7 @@ https://github.com/andrewlalis/handy-httpd
 https://andrewlalis.github.io/handy-httpd/guide/
 https://andrewlalis.github.io/handy-httpd/guide/
 
 
 
 
-
+http://127.0.0.1:8080/
 ```
 ```
 
 
 
 

+ 34 - 2
htest/source/app.d

@@ -1,17 +1,49 @@
 
 
 import std.stdio;
 import std.stdio;
-
 import std.conv;
 import std.conv;
 
 
+
+import slf4d;
 import handy_httpd;
 import handy_httpd;
+import handy_httpd.components.websocket;
+import handy_httpd.handlers.path_handler;
 import handy_httpd.handlers.file_resolving_handler;
 import handy_httpd.handlers.file_resolving_handler;
 
 
 
 
+
+class MyWebSocketHandler : WebSocketMessageHandler{
+  override void onConnectionEstablished(WebSocketConnection conn, in HttpRequest request){
+    infoF!"Connection established with id %s"(conn.id); // id 8a4429e7-19b8-4dc4-bca6-14f64a471392
+    conn.sendTextMessage("Hey yourself!");
+  }
+  
+  override void onTextMessage(WebSocketTextMessage msg){
+    infoF!"Got TEXT: %s"(msg.payload);
+    //msg.conn.sendTextMessage("Hey yourself!");
+    msg.conn.sendTextMessage(msg.payload ~ " :)");
+  }
+  
+  override void onCloseMessage(WebSocketCloseMessage msg){
+    infoF!"Closed: %d, %s"(msg.statusCode, msg.message);
+  }
+}
+
+
 void main(string[] args){
 void main(string[] args){
   ServerConfig cfg;
   ServerConfig cfg;
   if(args.length > 1){
   if(args.length > 1){
     cfg.port = args[1].to!ushort;
     cfg.port = args[1].to!ushort;
   }
   }
-  new HttpServer(new FileResolvingHandler("public"), cfg).start();
+  
+  cfg.workerPoolSize = 3;
+  cfg.enableWebSockets = true; // Important! Websockets won't work unless `enableWebSockets` is set to true!
+  WebSocketHandler handler = new WebSocketHandler(new MyWebSocketHandler());
+  
+  //new HttpServer(new FileResolvingHandler("public"), cfg).start();
+  PathHandler pathHandler = new PathHandler()
+    .addMapping(Method.GET, "/ws", handler)
+    .addMapping("/**", new FileResolvingHandler("public"));
+  
+  new HttpServer(pathHandler, cfg).start();
 }
 }