angular6使用sockjs-client+stompjs进行websocket连接的方法

安装sockjs、stompjs

  • npm install sockjs-client --save
  • npm install stompjs --save

引入

  • import SockJS from 'sockjs-client';
  • import Stomp from 'stompjs';

使用

 this.socket = new SockJS(`/iot-mdg/gs-topic-websocket?access-token=${token}`);
    this.stompClient = Stomp.over(this.socket);
    this.stompClient.connect({}, (frame) => {
      console.log('Connected: ' + frame);
      this.stompClient.subscribe('/topic/workData/xxxxxxxxxx', function (greeting) {
        console.log(greeting);
        // showGreeting(greeting.body);
      });
      this.stompClient.send("/websocket/subWorkData", {}, JSON.stringify({ 'deviceId': 'xxxxxxxxxx' }));
    });

遇到的问题

  • ERROR in ./node_modules/stompjs/lib/stomp-node.js Module not found: Error: Can't resolve 'net' in 'D:\sky\iot-web\node_modules\stompjs\lib'

    • 解决办法 npm i net -S
  • browser-crypto.js:3 Uncaught ReferenceError: global is not defined at Object../node_modules/sockjs-client/lib/utils/browser-crypto.js (browser-crypto.js:3) at __webpack_require__ (bootstrap:81) at Object../node_modules/sockjs-client/lib/utils/random.js (random.js:4) at __webpack_require__ (bootstrap:81) at Object../node_modules/sockjs-client/lib/utils/event.js (event.js:3) at __webpack_require__ (bootstrap:81) at Object../node_modules/sockjs-client/lib/transport/websocket.js (websocket.js:3) at __webpack_require__ (bootstrap:81) at Object../node_modules/sockjs-client/lib/transport-list.js (transport-list.js:5) at __webpack_require__ (bootstrap:81)

    • 解决办法 在polyfills.ts 文件中添加(window as any).global = window;

你可能感兴趣的:(前端)