Skip to content

Instantly share code, notes, and snippets.

@emilwidlund
Last active November 26, 2018 09:53
Show Gist options
  • Select an option

  • Save emilwidlund/2eb606d66d978025edb3a6a44bd1f425 to your computer and use it in GitHub Desktop.

Select an option

Save emilwidlund/2eb606d66d978025edb3a6a44bd1f425 to your computer and use it in GitHub Desktop.
// Import http and ws modules
const http = require('http');
const WebSocket = require('ws');
// Create an http server
const server = new http.createServer();
// Create a WebSocket server by wrapping the http server
const wss = new WebSocket.Server({ server });
// Setup a listener for new connections
wss.on('connection', (ws) => {
// When a client connects, we listen for messages from that client
ws.on('message', (data) => {
// Parse the message payload and log it to the console
console.log(JSON.parse(data));
// When a message is sent by a client, simply loop through all connected clients and forward the message
// except the client who sent the message
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});
// Start the server on port 8081
server.listen(8081, () => {
console.log('Chat server now running on http://localhost:8081');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment