Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created December 17, 2013 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/8009966 to your computer and use it in GitHub Desktop.
Save joyrexus/8009966 to your computer and use it in GitHub Desktop.
Simple websocket client/server demo

Simple demo of a node-based websocket client and server using ws.

Our server sends out a timestamp once a second and our client simply prints out any messages it receives.

Install ws:

npm install -g ws

Running the server:

# server.coffee 
websocket server created -> ws://localhost:8081
use CTRL-C to quit
connection open
connection closed
^C

Running the client:

# client.coffee 
connected (use CTRL+C to quit)
"2013-12-17T18:03:56.943Z"
"2013-12-17T18:03:57.945Z"
"2013-12-17T18:03:58.946Z"
"2013-12-17T18:03:59.947Z"
^C

Connecting to the server with wscat:

# wscat -c ws://localhost:8081
connected (press CTRL+C to quit)
< "2013-12-17T18:11:11.124Z"
< "2013-12-17T18:11:12.127Z"
< "2013-12-17T18:11:13.128Z"
< "2013-12-17T18:11:14.129Z"
> ^C
#!/usr/bin/env coffee
WebSocket = require('ws')
stream = new WebSocket 'ws://localhost:8081'
stream
.on('open', -> console.log 'connected (use CTRL+C to quit)')
.on('message', (msg) -> console.log msg)
#!/usr/bin/env coffee
WebSocketServer = require('ws').Server
wss = new WebSocketServer(port: 8081)
console.log 'websocket server created -> ws://localhost:8081'
console.log 'use CTRL-C to quit'
wss.on('connection', (ws) ->
console.log 'connection open (press CTRL+C to quit)'
timestamp = -> ws.send JSON.stringify(new Date())
id = setInterval timestamp, 1000
ws.on 'close', ->
console.log 'connection closed'
clearInterval id
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment