index.html 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Socket</title>
  5. </head>
  6. <body">
  7. <div><input type="text" id="textin"><button onclick="send()">Submit</button> <button onclick="Broadcast()">Submit to room</button></div>
  8. <input type="text" id="roomid"><button onclick="joinTheRoom()">JOIN</button><br />
  9. <input type="text" id="WS-SERVER" value="ws://localhost:3000"><button onclick="InitWS()">Connect</button>
  10. <script>
  11. aROOM = 0
  12. function joinTheRoom(){
  13. aROOM = document.getElementById('roomid').value;
  14. var Datas = {'tag': 'setRoom', 'msg': aROOM, 'opt': true};
  15. ws.send(JSON.stringify(Datas));
  16. console.log("Join to room " + aROOM);
  17. // 结果返回
  18. }
  19. function send(){
  20. var context = document.getElementById('textin').value;
  21. var data = {'tag': 'public', 'msg': context, 'opt': false};
  22. ws.send(JSON.stringify(data));
  23. }
  24. function Broadcast(){
  25. var context = document.getElementById('textin').value;
  26. var data = {'tag': 'roomcast', 'msg': context, 'opt': true, 'arg': {'roomid': aROOM}};
  27. ws.send(JSON.stringify(data));
  28. }
  29. function InitWS(){
  30. if("WebSocket" in window){
  31. console.log("您的浏览器支持Websocket");
  32. ws = new WebSocket(document.getElementById('WS-SERVER').value);
  33. ws.onopen = function(){
  34. console.log("connected!");
  35. }
  36. ws.onmessage = function(evt){
  37. var rece = evt.data;
  38. console.log("received: "+ rece);
  39. }
  40. ws.onclose = function(){
  41. console.log("disconnected!");
  42. }
  43. }else{
  44. alert("您的浏览器不支持Websocket");
  45. }
  46. }
  47. </script>
  48. </body>
  49. </html>