websocket.js 1.5 KB

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