Created
May 5, 2019 13:13
-
-
Save zprima/747cc7c9ebb310bbd043bdf23afecaa4 to your computer and use it in GitHub Desktop.
medium_p6_c1
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 utils = require("./utils.js"); | |
const myClient = require("./client.js"); | |
const WebSocket = require("ws"); | |
const chalk = require("chalk"); | |
const wss = new WebSocket.Server({ port: 8080, clientTracking: true }); | |
function clientConnected(client) { | |
var colorify = chalk.hex(client.color); | |
console.log(`a client connected (${colorify(client.name)})`); | |
} | |
function sendInitMsg(ws, client) { | |
ws.send( | |
JSON.stringify({ | |
name: client.name, | |
color: client.color, | |
msg: `Welcome, ${client.name}`, | |
msgType: "init" | |
}) | |
); | |
} | |
function broadcastAll(data) { | |
wss.clients.forEach(function each(client) { | |
if (client.readyState === WebSocket.OPEN) { | |
client.send(data); | |
} | |
}); | |
} | |
wss.on("listening", () => { | |
console.log(chalk.green("Server listening")); | |
}); | |
wss.on("connection", function connection(ws) { | |
var client = new myClient.Client(); | |
clientConnected(client); | |
sendInitMsg(ws, client); | |
ws.on("message", function incoming(message) { | |
var json_data = utils.handleReceivedMsg(message); | |
broadcastAll(json_data); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment