Skip to content

it is an example of implementing websocket(ws) on both server and client side

Notifications You must be signed in to change notification settings

wahengchang/nodejs-websocket-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nodejs-websocket-example

it is an example of implementing websocket(ws) on both server and client side

Install

$ npm install --save ws express
or 
$ git clone [email protected]:wahengchang/nodejs-websocket-example.git

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

client

websocket client is a browser supported object.

There are 3 basic must know fucntions:

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

server

server code is simple.

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

Run

Run server

$ npm start

Open browser

http://localhost:3000/

image

Reference

About

it is an example of implementing websocket(ws) on both server and client side

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published