Skip to content

Instantly share code, notes, and snippets.

@midnightcodr
Last active August 15, 2023 20:30
Show Gist options
  • Save midnightcodr/c6f83e52a642da1189de4d58881fe01c to your computer and use it in GitHub Desktop.
Save midnightcodr/c6f83e52a642da1189de4d58881fe01c to your computer and use it in GitHub Desktop.
websocket performance test using ws
npm install bluebird ws
node server.js
node client.js
const Promise = require('bluebird')
const WebSocket = require('ws')
const nbr = 200
const now = () => {
return new Date().getTime()
}
function Client(id) {
this.ws = null
this.start = function() {
const that = this
this.ws = new WebSocket('ws://10.1.8.87:8080')
//this.ws = new WebSocket('ws://localhost:8080')
this.ws.on('open', function() {
console.log(`client ${id} connected`)
that.send()
that.ws.on('message', function(data) {
var msg=JSON.parse(data)
if(msg.start) {
msg.roudntrip=now() - msg.start // roundtrip time in ms
data=JSON.stringify(msg)
}
console.log('received from server: ', data)
setTimeout(function() {
that.send()
}, Math.random()*1000)
})
})
}
this.send = function() {
const data = {
move: {
x: Math.random(),
y: Math.random()
},
start: now()
}
this.ws.send(JSON.stringify(data))
}
}
const ids = Array.from(new Array(nbr), (x,i) => i)
Promise.map(ids, (id) => {
const c = new Client(id)
c.start()
return Promise.resolve()
}).then(() => {
console.log('all up')
})
const WebSocket = require('ws')
const wss = new WebSocket.Server({
port: 8080
})
const now = () => {
return new Date().getTime()
}
wss.on('connection', (ws) => {
ws.on('message', function(data) {
var msg=JSON.parse(data)
msg.took=now() - msg.start // time in ms from client to server
ws.send(JSON.stringify(msg))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment