| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- function WebSocketClient() {
- }
- WebSocketClient.prototype._generateEndpoint = function () {
- let protocol = location.protocol
- let hostname = location.hostname
- let port = location.port
- let prefix;
- if (protocol === 'https') {
- if (port === 443) {
- prefix = 'wss://' + hostname;
- } else {
- prefix = 'wss://' + hostname + ':' + port;
- }
- } else {
- if (port === 80) {
- prefix = 'ws://' + hostname;
- } else {
- prefix = 'ws://' + hostname + ':' + port;
- }
- }
- var host1 = window.location.host
- var url = 'wss://' + host1 + '/ws/ssh?token=12345678'
- return url;
- };
- WebSocketClient.prototype.connect = function (options) {
- let endpoint = this._generateEndpoint();
- if (window.WebSocket) {
- // 如果支持websocket
- this._connection = new WebSocket(endpoint);
- } else {
- //否则报错
- options.onError('WebSocket Not Supported');
- return;
- }
- this._connection.onopen = function () {
- options.onConnect();
- };
- this._connection.onmessage = function (evt) {
- var data = evt.data.toString();
- //data = base64.decode(data);
- options.onData(data);
- };
- this._connection.onclose = function (evt) {
- options.onClose();
- };
- };
- WebSocketClient.prototype.send = function (data) {
- this._connection.send(JSON.stringify(data));
- };
- WebSocketClient.prototype.sendInitData = function (options) {
- //连接参数
- this._connection.send(JSON.stringify(options));
- }
- WebSocketClient.prototype.sendClientData = function (data) {
- //发送指令
- this._connection.send(JSON.stringify({"ops": "command", "command": data}))
- }
- var wsClient = new WebSocketClient();
|