Created
May 5, 2016 19:46
-
-
Save sethdorris/b72685f603c4cc3d269475d2cc09b5d4 to your computer and use it in GitHub Desktop.
eeeeew don't judge me
This file contains 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
import express from "express"; | |
import url from 'url'; | |
import path from 'path'; | |
const WebSocketServer = require('ws').Server; | |
const http = require('http').Server(app); | |
const wss = new WebSocketServer({ | |
server: http | |
}); | |
const app = express(); | |
app.use(express.static(path.resolve('../'))); | |
let users = []; | |
app.get('/', (req, res) => { | |
res.sendFile(path.resolve("../index.html"), {}, | |
(err) => { | |
if (err) { | |
console.log("Error grabbing Index", err); | |
} | |
} | |
); | |
}); | |
wss.broadcast = (data) => { | |
wss.clients.forEach((client) => { | |
client.send(JSON.stringify(data)); | |
}); | |
}; | |
wss.on('connection', (ws) => { | |
console.log(ws); | |
ws.on('message', (message) => { | |
let messageparse = JSON.parse(message); | |
console.log(messageparse); | |
switch (messageparse.type) { | |
case "USER_CONNECTED": | |
let messageobject = { | |
type: "FROMSERVER_USERCONNECTED", | |
users: users | |
} | |
users.push({username: messageparse.username}); | |
wss.broadcast(messageobject); | |
break; | |
case "SEND_MESSAGE": | |
let message = { | |
type: "FROMSERVER_NEWMESSAGE", | |
content: messageparse.content | |
} | |
wss.broadcast(message); | |
break; | |
default: | |
ws.send(JSON.stringify({Error: "Could not handle your message."})) | |
} | |
}) | |
}) | |
http.on('request', app); | |
http.listen(3000, () => { | |
console.log("Listening on " + http.address().port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment