WebSocket.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var websocket = {
  2. sock: null,
  3. on_open: function () {
  4. this.send_data(JSON.stringify({
  5. stype: "auth",
  6. ctype: "login",
  7. data: {
  8. name: "TestUser",
  9. pwd: 123456
  10. }
  11. }));
  12. },
  13. on_message: function (event) {
  14. // console.log("client rcv data=" + event.data);
  15. this.host.updateMsg(event.data);
  16. },
  17. on_close: function () {
  18. this.close();
  19. },
  20. on_error: function () {
  21. this.close();
  22. },
  23. close: function () {
  24. if(this.sock){
  25. this.sock.close();
  26. this.sock = null;
  27. }
  28. },
  29. connect: function (url,host) {
  30. this.host = host;
  31. this.sock = new WebSocket(url);
  32. this.sock.binaryType = "arraybuffer";
  33. this.sock.onopen = this.on_open.bind(this);
  34. this.sock.onmessage = this.on_message.bind(this);
  35. this.sock.onclose = this.on_close.bind(this);
  36. this.sock.onerror = this.on_error.bind(this);
  37. },
  38. send_data: function (data) {
  39. this.sock.send(data);
  40. }
  41. };
  42. module.exports = websocket;