How to use primus - 10 common examples

To help you get started, we’ve selected a few primus examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github actionhero / actionhero / test / integration / shared_fingerprint.js View on Github external
let connectClient = async (transportOptions) => {
  // get actionheroClient in scope
  const ActionheroClient = eval(api.servers.servers.websocket.compileActionheroClientJS()) // eslint-disable-line

  let S = _Primus.createSocket()
  let clientSocket = new S('http://localhost:' + api.config.servers.web.port, {transport: transportOptions})

  let client = new ActionheroClient({}, clientSocket) // eslint-disable-line
  // await new Promise((resolve) => { setTimeout(resolve, 100) })
  let connectResponse = await new Promise((resolve, reject) => {
    client.connect((error, connectResponse) => {
      if (error) { return reject(error) }
      resolve(connectResponse)
    })
  })

  return {client, connectResponse}
}
github flow-typed / flow-typed / definitions / npm / primus_v5.x.x / test_primus-v5.js View on Github external
// @flow
import Primus from 'primus';
import http from 'http';

const primus: Primus = new Primus(new http.Server());
(primus.clients(): string[]);
(primus.write(123): void);
(primus.save('path'): void);
primus.forEach((spark: Primus$Spark, id: string, connections: any) => {
  (spark.id: string);
  (spark.query: string);
  (spark.write('foo'): void);
  // $ExpectError
  spark.on(123, () => ({}));
});
// $ExpectError
primus.remove(123);

primus.use('testPlugin', {});
github ListnPlay / riot-isomorphic / src / app / util / socket.js View on Github external
initWithUrl(url) {
        this.url = url;
        this.client = null;

        if (typeof window != 'undefined') {
            // Client init
            console.log("Socket util - Client init with URL: ", url);
            this.client = Primus.connect('http://localhost:3000');
        } else {
            // Server init
            console.log("Socket util - Server init with URL: ", url);
            let Socket = PrimusNode.createSocket({
                transformer: 'websockets',
                parser: 'json',
                plugin: {
                    'emitter' : PrimusEmitter
                }
            });
            this.client = new Socket(url);
        }
        this.client.on('open', () => {
            console.log("Socket connection is open");
        });
        this.client.on('error', (error) => {
            console.log('Error connecting to socket', error);
        });
    }
github difysjs / difys / src / Modules / Connection / Socket.js View on Github external
// import HttpsProxyAgent from "https-proxy-agent";
import Primus from "primus";
import { modules, constants, general } from "../../Config";
import store from "../Store";
import { logger, EventEmitter } from "../../Libs";

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

export default class Socket extends PrimusSocket {
	constructor(sessionID, username) {
		const state = store.getState();
		const account = state.accounts[username];
		const phase = account.status;
		const socketUrl = Socket.getUrl(phase, account, sessionID);
		const socketOptions = modules.socket.options();
		super(socketUrl, socketOptions);
		this.phase = phase;
		this.account = {
			username,
			salt: "",
			key: []
github snyk / broker / lib / client / socket.js View on Github external
require('../patch-https-request-for-proxying');

const Primus = require('primus');
const relay = require('../relay');
const Socket = Primus.createSocket({
  transformer: 'engine.io',
  parser: 'EJSON',
  plugin: {
    'emitter': require('primus-emitter'),
  }
});
const logger = require('../log');

module.exports = ({ url, token, filters, config, identifyingMetadata }) => {
  if (!token) { // null, undefined, empty, etc.
    logger.error({ token }, 'missing client token');
    const error = new ReferenceError('BROKER_TOKEN is required to successfully identify itself to the server');
    error.code = 'MISSING_BROKER_TOKEN';
    throw error;
  }
github Alethio / ethstats-network-server / app / server.js View on Github external
initPrimus() {
    this.primusServer = new Primus(this.primusHttpServer, {
      transformer: 'websockets',
      pathname: '/api',
      parser: 'JSON',
      pingInterval: false, // native primus ping-pong disabled, custom ping pong implemented due to custom protocol
      maxLength: 31457280,
      plugin: {
        responder: primusResponder
      }
    });

    this.primusServer.on('initialised', () => {
      this.log.info('Primus server initialised');

      setInterval(() => {
        Object.keys(this.clients).forEach(sparkId => {
          let lastPingTimestamp = Date.now();
github angular-fullstack / generator-angular-fullstack / templates / app / server / config / websockets(ws).js View on Github external
export default function initWebSocketServer(server) {
    primus = new Primus(server, {});
    primus.plugin('emit', primusEmit);

    primus.on('connection', onConnect);
    primus.on('disconnection', onDisconnect);

    if(process.env.NODE_ENV === 'development') {
        return new Promise((resolve, reject) => {
            // Save the primus client library configured for our server settings
            primus.save(path.join(__dirname, '../../client/components/socket/primus.js'), err => {
                if(err) return reject(err);

                resolve(primus);
            });
        });
    } else {
        return Promise.resolve(primus);
github StellarFw / stellar / src / servers / websocket.js View on Github external
start (callback) {
    let self = this
    let webserver = self.api.servers.servers.web

    // create a new primus instance
    self.server = new Primus(webserver.server, self.api.config.servers.websocket.server)

    // define some event handlers
    self.server.on('connection', rawConnection => self._handleConnection(rawConnection))
    self.server.on('disconnection', rawConnection => self._handleDisconnection(rawConnection))

    self.api.log(`webSocket bound to ${webserver.options.bindIP}:${webserver.options.port}`, 'debug')
    self.server.active = true

    // write client js
    self._writeClientJS()

    // execute the callback
    callback()
  }
github c3subtitles / L2S2 / server / src / entry.js View on Github external
/* eslint-disable no-sync */
  server = https.createServer({
    key: fs.readFileSync(process.env.SSLKEY),
    cert: fs.readFileSync(process.env.SSLCERT),
  }, global.app.callback());
  /* eslint-enable no-sync */
} else {
  server = http.createServer(global.app.callback());
}
const options = {
  transformer: 'engine.io',
  compression: true,
};
global.router = new router();

global.primus = new Primus(server, options);
global.primus.use('emit', require('primus-emit'));
global.primus.use('rooms', require('primus-rooms'));

global.primus.on('connection', require('./primus/connections').onConnection);

global.primus.save(path.resolve('./primusClient.js'));


require('./routes.js');

global.app
.use(koaJSON())
.use(async (ctx, next) => {
  try {
    await next();
  } catch (e) {
github peeriodproject / core / src / core / ui / UiManager.js View on Github external
UiManager.prototype._setupSocketServer = function () {
        this._socketServer = new PrimusIo(this._httpServer, {
            port: this._config.get('ui.UiManager.socketServer.port'),
            transformer: this._config.get('ui.UiManager.socketServer.transformer'),
            parser: this._config.get('ui.UiManager.socketServer.parser')
        });

        var staticPublicPath = this._config.get('ui.UiManager.staticServer.publicPath');
        var clientLibPath = path.resolve(path.join(staticPublicPath, 'primus.io.js'));

        // todo check if file exists
        this._socketServer.save(clientLibPath);

        this._setupSocketChannelComponentMap();
        this._setupSocketChannels();
    };

primus

Primus is a simple abstraction around real-time frameworks. It allows you to easily switch between different frameworks without any code changes.

MIT
Latest version published 1 year ago

Package Health Score

66 / 100
Full package analysis