[Node.js] set up Websocket + Express + HTML service in 3 step

Written by peterchang_82818 | Published 2017/10/31
Tech Story Tags: nodejs | express | websocket | tutorial | react

TLDRvia the TL;DR App

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).

Step1 : Set up Express server

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!')})

Step2 : Set up Client HTML File

websocket client is a browser supported object.

Below is goind to introduce 3 importand fucntion:

  • ws.onopen : emmited when connected
  • ws.send : sending a send event to websocket server
  • ws.onmessage : event emmited when receiving message

(Read More)

<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>

Step3 : Set up Websocket service

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)})

Being a lazy guy

$ git clone [email protected]:wahengchang/nodejs-websocket-example.git

$ npm install

$ npm start

Open browser

http://localhost:3000/

Unstanding ws

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)).

Reference


Published by HackerNoon on 2017/10/31