Created
December 11, 2022 21:26
-
-
Save sereyn/be14e000d612209ff93f05c8865977c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! I will workaround this.