Skip to content

Instantly share code, notes, and snippets.

@sereyn
Created December 11, 2022 21:26
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 sereyn/be14e000d612209ff93f05c8865977c4 to your computer and use it in GitHub Desktop.
Save sereyn/be14e000d612209ff93f05c8865977c4 to your computer and use it in GitHub Desktop.
const WebSocketServer = require('websocket').server
const WebSocketClient = require('websocket').client
const http = require('http')
const command = process.argv[2]
if (command === undefined) {
console.log('Please provide a command: server or client')
process.exit(1)
}
if (command === 'server') {
serverCmd()
} else if (command === 'client') {
clientCmd()
} else {
console.error(`${command} not found`)
process.exit(1)
}
function serverCmd() {
const server = http.createServer((_, res) => {
res.writeHead(404)
res.end()
})
server.listen(8080, () => {
console.log('Listening on port 8080')
})
const wsServer = new WebSocketServer({ httpServer: server })
wsServer.on('request', request => {
const client = request.accept()
client.on('message', message => {
console.log('Received message:', message.utf8Data)
client.sendUTF('Hello, world!')
})
client.on('close', () => {
console.log('Connection closed')
})
})
}
function clientCmd() {
const client = new WebSocketClient()
client.on('connectFailed', err => {
console.error('Connect error:', err)
})
client.on('connect', connection => {
console.log('Connected')
connection.on('error', err => {
console.error('Connection error:', err)
})
connection.on('close', () => {
console.log('Connection closed')
})
connection.on('message', message => {
console.log('Received message:', message.utf8Data)
})
connection.sendUTF('Hello, world!')
})
client.connect('ws://localhost:8080')
}
@argahsuknesib
Copy link

Thanks! I will workaround this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment