12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- var WebsocketServer = require('websocket').server;
- var http = require('http');
- var server = http.createServer();
- const PORT = 3000 || process.env.PORT
- clientsList = [];
- server.listen(PORT, () => {
- console.log("Server running on http://localhost:" + PORT);
- });
- var wsServer = new WebsocketServer({httpServer:server});
- wsServer.on('request', (websocketRequest) => {
- var connection = websocketRequest.accept(null, 'accepted-origin');
- clientsList.push(connection);
- console.log('A client connected');
- connection.on('message', (msg) => {
- if(msg.type == 'utf8'){
- try {
- cd = JSON.parse(msg.utf8Data);
- if(cd.tag == 'setRoom' && cd.opt == true){
- if(connection.roomid == undefined){
- connection.roomid = cd.msg;
- }
- console.log("Set! roomid = " + connection.roomid);
- }
- if(cd.tag == 'roomcast' && cd.opt == true && cd.arg != undefined){
- console.log('Cast!')
- BroadcastInRoom(cd.arg.roomid, 'cast', cd.msg);
- }else if(cd.opt == true && (cd.arg == undefined || cd.arg == "")){
- console.log('Cannot GET arg');
- }else{
- console.log('Unknown ERROR');
- }
-
- if(cd.opt == false){
- clientsList.forEach(element => {
- element.sendUTF(cd.msg);
- });
- }
- console.log(cd);
- } catch (error) {
- console.log(error);
- console.error('Illegal Data');
- }
- }else{
- console.log(msg);
- }
- });
- connection.on('close', (reasonCode, description) => {
- console.log('A client disconnected');
- });
- })
- function BroadcastInRoom(roomid, tag, msg){
- clientsList.forEach(element => {
- if(element.roomid == roomid){
- element.send(JSON.stringify({'tag': tag, 'msg': msg}));
- }
- });
- console.log("CAST!!!!")
- }
|