forked from ringo/ringojs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add examples/websocket-server-push.js
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
// Simple websocket server demo | ||
var response = require("ringo/jsgi/response"); | ||
var arrays = require("ringo/utils/arrays"); | ||
|
||
var connections = []; | ||
|
||
// Schedule an interval function that periodically broadcasts the number of open connections | ||
setInterval(function() { | ||
connections.forEach(function(conn) { | ||
conn.send((connections.length - 1) + " other connection(s) open"); | ||
}); | ||
}, 5000) | ||
|
||
exports.app = function(req) { | ||
return response.static(module.resolve("html/websocket.html"), "text/html"); | ||
}; | ||
|
||
function onconnect(conn) { | ||
conn.addListener("open", function() { | ||
connections.push(conn); | ||
console.info("Opening connection, " + connections.length + " open"); | ||
}); | ||
conn.addListener("message", function(message) { | ||
connections.forEach(function(conn) { | ||
conn.send(message); | ||
}); | ||
console.info("Sending message"); | ||
}); | ||
conn.addListener("close", function() { | ||
arrays.remove(connections, conn); | ||
console.info("Closing connection, " + connections.length + " remaining"); | ||
}) | ||
} | ||
|
||
if (require.main == module) { | ||
var server = require("ringo/httpserver").main(module.id); | ||
server.getDefaultContext().addWebSocket("/websocket", onconnect); | ||
} |