websocket nodejs serve rclient browser
Web Sockets are probably in use more around you now than you think, most things with real-time interactions are most probably running through these little gems.
They’re great for instant transfers of data from one machine to one or many other connected clients, used in things like instant chats, collaborative sketch environments and many more (from).
Express takes the role of HTTP server, serving HTML file and wiring Websocket service
var express = require('express')
var ws = require('./ws')
var app = express()
app.get('/', function (req, res) {res.sendfile(__dirname + '/ws.html');})
app.listen(3000, function () {console.log('Example app listening on port 3000!')})
websocket client
is a browser supported object.
Below is goind to introduce 3 importand fucntion:
ws.onopen
: emmited when connectedws.send
: sending a send event to websocket serverws.onmessage
: event emmited when receiving message
<script>var ws = new WebSocket('ws://localhost:40510');
// event emmited when connected
ws.onopen = function () {
console.log('websocket is connected ...')
// sending a send event to websocket server
ws.send('connected')
}
// event emmited when receiving message
ws.onmessage = function (ev) {
console.log(ev);
}
</script>
server code is simple, I think you would understand
var WebSocketServer = require('ws').Server,wss = new WebSocketServer({port: 40510})
wss.on('connection', function (ws) {ws.on('message', function (message) {console.log('received: %s', message)})
setInterval(() => ws.send(`${new Date()}`),1000)})
$ git clone [email protected]:wahengchang/nodejs-websocket-example.git
$ npm install
$ npm start
Open browser
http://localhost:3000/
ws
is a WebSocket client and server implementation, fast, and easy to use ([R]ead More](https://stackoverflow.com/questions/16392260/which-websocket-library-to-use-with-node-js)).