main.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. window.onload = function(){
  2. InitWS();
  3. }
  4. aROOM = 0
  5. function joinTheRoom(){
  6. aROOM = document.getElementById('roomid').value;
  7. var Datas = {'tag': 'setRoom', 'msg': aROOM, 'opt': true};
  8. ws.send(JSON.stringify(Datas));
  9. console.log("Join to room " + aROOM);
  10. // 结果返回
  11. }
  12. function send(){
  13. var context = document.getElementById('textin').value;
  14. var data = {'tag': 'public', 'msg': context, 'opt': false};
  15. ws.send(JSON.stringify(data));
  16. }
  17. function Broadcast(){
  18. var context = document.getElementById('textin').value;
  19. var data = {'tag': 'roomcast', 'msg': context, 'opt': true, 'arg': {'roomid': aROOM}};
  20. ws.send(JSON.stringify(data));
  21. }
  22. function InitWS(){
  23. if("WebSocket" in window){
  24. console.log("您的浏览器支持Websocket");
  25. ws = new WebSocket("ws://localhost:3000");
  26. ws.onopen = function(){
  27. console.log("connected!");
  28. }
  29. ws.onmessage = function(evt){
  30. var rece = evt.data;
  31. console.log("received: "+ rece);
  32. }
  33. ws.onclose = function(){
  34. console.log("disconnected!");
  35. }
  36. }else{
  37. alert("您的浏览器不支持Websocket");
  38. }
  39. }