Last active
December 20, 2015 18:58
-
-
Save pk11/6179319 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//imports excluded for brevity | |
var websocket = new BaseWebSocketHandler() { | |
connectionCount: 1, | |
//note: webbit is single-threaded | |
//you may need to change this to ConcurrentHashMap | |
//if `connections` is accessed from worker threads | |
connections: new HashMap(), | |
onOpen: function (connection) { | |
connection.send("Number of active connections: " + this.connectionCount ); | |
this.connectionCount++; | |
this.connections.put(connection.hashCode(), connection); | |
}, | |
onClose: function (connection) { | |
this.connectionCount--; | |
this.connections.remove(connection.hashCode()); | |
}, | |
onMessage: function (connection, message) { | |
print("message arrived: "+message); | |
var conns = Java.from(this.connections.values()); | |
for (var i = 0; i < conns.length; i++) { | |
conns[i].send(message.toUpperCase()); | |
} | |
} | |
}; | |
var helloworld = new HttpHandler { | |
handleHttpRequest: function (request, response, control) { | |
//note: webbit is single-threaded | |
//this essentially means execute a block of code on next tick. | |
//Also, as per jlaskey, js closures act the same way as java8 lambdas when it comes to SAM types, | |
//so `execute` can take a function | |
control.execute(function () { | |
response.content("Hello World").end(); | |
}); | |
} | |
}; | |
var webServer = createWebServer(9000). | |
add("/websockets", websocket). | |
add("/hello", helloworld). | |
add(new StaticFileHandler("./public")); | |
webServer.start(); | |
print("Server running at " + webServer.getUri()); | |
Thread.currentThread().join(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment