websocket.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function WebSocketClient() {
  2. }
  3. WebSocketClient.prototype._generateEndpoint = function () {
  4. let protocol = location.protocol
  5. let hostname = location.hostname
  6. let port = location.port
  7. let prefix;
  8. if (protocol === 'https') {
  9. if (port === 443) {
  10. prefix = 'wss://' + hostname;
  11. } else {
  12. prefix = 'wss://' + hostname + ':' + port;
  13. }
  14. } else {
  15. if (port === 80) {
  16. prefix = 'ws://' + hostname;
  17. } else {
  18. prefix = 'ws://' + hostname + ':' + port;
  19. }
  20. }
  21. var host1 = window.location.host
  22. var url = 'wss://' + host1 + '/ws/ssh?token=12345678'
  23. return url;
  24. };
  25. WebSocketClient.prototype.connect = function (options) {
  26. let endpoint = this._generateEndpoint();
  27. if (window.WebSocket) {
  28. // 如果支持websocket
  29. this._connection = new WebSocket(endpoint);
  30. } else {
  31. //否则报错
  32. options.onError('WebSocket Not Supported');
  33. return;
  34. }
  35. this._connection.onopen = function () {
  36. options.onConnect();
  37. };
  38. this._connection.onmessage = function (evt) {
  39. var data = evt.data.toString();
  40. //data = base64.decode(data);
  41. options.onData(data);
  42. };
  43. this._connection.onclose = function (evt) {
  44. options.onClose();
  45. };
  46. };
  47. WebSocketClient.prototype.send = function (data) {
  48. this._connection.send(JSON.stringify(data));
  49. };
  50. WebSocketClient.prototype.sendInitData = function (options) {
  51. //连接参数
  52. this._connection.send(JSON.stringify(options));
  53. }
  54. WebSocketClient.prototype.sendClientData = function (data) {
  55. //发送指令
  56. this._connection.send(JSON.stringify({"ops": "command", "command": data}))
  57. }
  58. var wsClient = new WebSocketClient();