如何在电子中使用primus

How to use primus in electron

我的目标是用electron做一个桌面应用。我已经在 nodejs 中有一个脚本,当我在 Nodejs 中 运行 它时,它可以工作,但是它在 electron 中阻塞,我知道 primus 是问题所在,但我不知道如何解决它。

我想在 websocket 中连接,因此我使用:

var url = "https://myurl.com"

const PrimusSocket = Primus.createSocket({transformer: "engine.io",});

const primus = new PrimusSocket(url);

但第二行不起作用,控制台中没有显示任何内容,除了不应阻止所有脚本的警告:

[Deprecation] 'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead.

我的 index.html 中的代码不起作用

   <script type="text/javascript" >
      async function test() {
        var Primus = require("primus")
         var url = "https://myurl.com";
         console.log("we create the socket");
         const PrimusSocket = Primus.createSocket({transformer: "engine.io",});
         console.log("new instance"); //this message doesn't show up
         const primus = new PrimusSocket(url);

         primus.on("open", () => {
           console.log("open");
         })
         primus.on("data", data => {
           console.log("message received : " + data._messageType);
         })
         primus.on("reconnected", () => {
           console.log('reconnect');
         })
         primus.on("error", error => {
           logger.error(new Error(error));
         })
         primus.on("end", () => {
           console.log("end");
         })
         primus.open();
       }
       test();
   </script>

对我来说它是这样工作的

服务器端

app.js

const = express();
const server = http.createServer(app);
// initWebSocketServer is a promise in websockets.js
// that is resolve when you create the library and save it where you want, 
const wsInitPromise = initWebSocketServer(server);
// Start server
function startServer() {
  app.angularFullstack = server.listen(config.port, config.ip, function() {
    console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
  });
}
// Start the server when Primus has been resolved
wsInitPromise.then(setImmediate(startServer)).catch(err => {
    console.log('Server failed to start due to error: %s', err);
  });

websockets.js

// primus-emit module adds client->server and server->client event emitting 
// to Primus
import primusEmit from 'primus-emit';

const registerFunctions = [
  // Any controller you add you should create a socket file where
  //  you register (spark, primus) in order to use it in each of 
  // your controller
  require('../api/discountRequest/discountRequest.socket').register,
  require('../api/discount/discount.socket').register,
  require('../api/paymentMethod/paymentMethod.socket').register,
  require('../api/invoice/invoice.socket').register,
];
function onDisconnect(spark) {}
function onConnect(spark) {
  spark.on('info', data => {
    spark.log(JSON.stringify(data, null, 2));
  });

  for(let register of registerFunctions) {
    // here you register all your paths to socket's file
    register(spark, primus);
  }
}
let primus;

export function broadcast(message) {
  primus.forEach(spark => {
    spark.emit('broadcast', message);
  });
}

export default function initWebSocketServer(server) {
  // primus needs to be "attached" to a HTTP compatible server (http and https), 
  //there is multiple transformer you can choose, from me I use websocket
  primus = new Primus(server, {
    transformer: 'websockets',
  });
  // add the primus-emit plugin
  primus.plugin('emit', primusEmit);
  // make some event on starting
  primus.on('connection', onConnect);
  primus.on('disconnection', onDisconnect);

  return new Promise((resolve, reject) => {
    // Save the primus client library configured for our server settings
    // create the library 
    primus.library();
    // store it somewhere in your server
    primus.save(path.join(__dirname, 'client/components/socket/primus.js'), err => {
      if(err) return reject(err);
       resolve();
    });
  }).catch(e => console.error(`.catch(${e})`));
}

客户端

index.html

// primus/primus.js is the default path to primus script 
<script defer src="https://your-server-url.com/primus/primus.js"></script>

你的脚本

checkConnection() {
  // if Primus library is not yet created so wait for it 
  if (typeof(Primus) !== "undefined") {
    this.primus = new Primus(/*server url with */, {});
    some default primus event
    this.primus.on('open', () => {
      console.log('Connection is alive and kicking');
    });
    this.primus.on('error', (err) => {
      console.error('Something horrible has happened', err.stack);
    });
    this.primus.on('reconnect', (opts) => {
      console.log('Reconnection attempt started');
      this.branchinfo();
    });
    this.primus.on('reconnect timeout', (err, opts) => {
      console.log('Timeout expired: %s', err.message);
    });
    this.primus.on('reconnect failed', (err, opts) => {
      console.log('The reconnection failed: %s', err.message);
    });
    this.primus.on('end', () => {
      console.log('Connection closed');
    });
  } else {
    setTimeout(() => {
      this.checkConnection();
    },1000);
  }
}