├── .gitignore ├── README.md ├── package.json ├── index.js └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | node_modules 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Node.js Websocket Test 2 | 3 | A tiny demo using the [einaros/ws](http://einaros.github.io/ws/) WebSockets implementation. 4 | 5 | # Running Locally 6 | 7 | ``` bash 8 | npm install 9 | npm start 10 | ``` 11 | 12 | # Running on Heroku 13 | 14 | ``` bash 15 | heroku create 16 | git push heroku master 17 | heroku open 18 | ``` 19 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ws-test", 3 | "version": "0.0.1", 4 | "repository": { 5 | "type": "git", 6 | "url": "https://github.com/heroku-examples/node-ws-test.git" 7 | }, 8 | "dependencies": { 9 | "express": "^4.4.5", 10 | "ws": "0.4.x" 11 | }, 12 | "engines": { 13 | "node": "0.10.x" 14 | }, 15 | "scripts": { 16 | "start": "node index.js" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var WebSocketServer = require("ws").Server 2 | var http = require("http") 3 | var express = require("express") 4 | var app = express() 5 | var port = process.env.PORT || 5000 6 | 7 | app.use(express.static(__dirname + "/")) 8 | 9 | var server = http.createServer(app) 10 | server.listen(port) 11 | 12 | console.log("http server listening on %d", port) 13 | 14 | var wss = new WebSocketServer({server: server}) 15 | console.log("websocket server created") 16 | 17 | wss.on("connection", function(ws) { 18 | var id = setInterval(function() { 19 | ws.send(JSON.stringify(new Date()), function() { }) 20 | }, 1000) 21 | 22 | console.log("websocket connection open") 23 | 24 | ws.on("close", function() { 25 | console.log("websocket connection close") 26 | clearInterval(id) 27 | }) 28 | }) 29 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 |
3 | 19 | 20 | 29 | 30 | 31 |