1

我的目标是用电子制作一个桌面应用程序。我已经在 nodejs 中有一个脚本,当我在 Nodejs 中运行它时它可以工作,但是在电子中阻塞,我知道 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>
4

1 回答 1

1

对我来说,它以这种方式工作

服务器端

应用程序.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})`));
}

客户端

索引.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);
  }
}
于 2019-12-17T11:28:08.763 回答