webssh.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. function WSSHClient() {
  2. }
  3. WSSHClient.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. return prefix + '/webssh';
  22. };
  23. WSSHClient.prototype.connect = function (options) {
  24. let endpoint = this._generateEndpoint();
  25. if (window.WebSocket) {
  26. // 如果支持websocket
  27. this._connection = new WebSocket(endpoint);
  28. } else {
  29. //否则报错
  30. options.onError('WebSocket Not Supported');
  31. return;
  32. }
  33. this._connection.onopen = function () {
  34. options.onConnect();
  35. };
  36. this._connection.onmessage = function (evt) {
  37. var data = evt.data.toString();
  38. //data = base64.decode(data);
  39. options.onData(data);
  40. };
  41. this._connection.onclose = function (evt) {
  42. options.onClose();
  43. };
  44. };
  45. WSSHClient.prototype.send = function (data) {
  46. this._connection.send(JSON.stringify(data));
  47. };
  48. WSSHClient.prototype.sendInitData = function (options) {
  49. //连接参数
  50. this._connection.send(JSON.stringify(options));
  51. }
  52. WSSHClient.prototype.sendClientData = function (data) {
  53. //发送指令
  54. this._connection.send(JSON.stringify({"ops": "command", "command": data}))
  55. }
  56. var client = new WSSHClient();