app.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var WebsocketServer = require('websocket').server;
  2. var http = require('http');
  3. var server = http.createServer();
  4. const PORT = 3000 || process.env.PORT
  5. clientsList = [];
  6. server.listen(PORT, () => {
  7. console.log("Server running on http://localhost:" + PORT);
  8. });
  9. var wsServer = new WebsocketServer({httpServer:server});
  10. wsServer.on('request', (websocketRequest) => {
  11. var connection = websocketRequest.accept(null, 'accepted-origin');
  12. clientsList.push(connection);
  13. console.log('A client connected');
  14. connection.on('message', (msg) => {
  15. if(msg.type == 'utf8'){
  16. try {
  17. cd = JSON.parse(msg.utf8Data);
  18. if(cd.tag == 'setRoom' && cd.opt == true){
  19. if(connection.roomid == undefined){
  20. connection.roomid = cd.msg;
  21. }
  22. console.log("Set! roomid = " + connection.roomid);
  23. }
  24. if(cd.tag == 'roomcast' && cd.opt == true && cd.arg != undefined){
  25. console.log('Cast!')
  26. BroadcastInRoom(cd.arg.roomid, 'cast', cd.msg);
  27. }else if(cd.opt == true && (cd.arg == undefined || cd.arg == "")){
  28. console.log('Cannot GET arg');
  29. }else{
  30. console.log('Unknown ERROR');
  31. }
  32. if(cd.opt == false){
  33. clientsList.forEach(element => {
  34. element.sendUTF(cd.msg);
  35. });
  36. }
  37. console.log(cd);
  38. } catch (error) {
  39. console.log(error);
  40. console.error('Illegal Data');
  41. }
  42. }else{
  43. console.log(msg);
  44. }
  45. });
  46. connection.on('close', (reasonCode, description) => {
  47. console.log('A client disconnected');
  48. });
  49. })
  50. function BroadcastInRoom(roomid, tag, msg){
  51. clientsList.forEach(element => {
  52. if(element.roomid == roomid){
  53. element.send(JSON.stringify({'tag': tag, 'msg': msg}));
  54. }
  55. });
  56. console.log("CAST!!!!")
  57. }