How to use the primus.createSocket function in primus

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 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 IdleLands / IdleLands3 / test / client / client.js View on Github external
const play = (name, index) => {
  const Socket = Primus.createSocket({
    transformer: 'websockets',
    parser: 'JSON',
    plugin: {
      rooms: require('primus-rooms'),
      emit: require('primus-emit'),
      multiplex: require('primus-multiplex')
    }
  });

  const socket = new Socket('ws://localhost:' + (process.env.PORT || 8080));

  const login = () => {
    const userId = `local|${name}`;
    socket.emit('plugin:player:login', { name, userId });
    socket.emit('plugin:player:request:pets');
  };
github devalpha-io / devalpha-node / __tests__ / devalpha.spec.ts View on Github external
let clientEvents = []
  const serverEvents = []
  let runTime = -1

  const trader = createTrader({
    feeds: {
      events: [{ timestamp: 0 }, { timestamp: 1 }]
    },
    dashboard: {
      active: true
    }
  }, () => {
    serverEvents.push('a')
  }).resume()

  const Socket = primus.createSocket({
    transformer: 'sockjs'
  });

  const socket = new Socket(`http://localhost:${SOCKET_PORT}`, {
    manual: true
  })

  expect(serverEvents.length).toBe(0)
  expect(clientEvents.length).toBe(0)

  socket.on('data', ({ type, payload }: any) => {
    if (type === DASHBOARD_EVENTS) {
      clientEvents = [...clientEvents, ...payload.events]
    } else if (type === DASHBOARD_FINISHED) {
      runTime = payload.finishedAt - payload.startedAt
    }
github goerli / ethstats-client / lib / node.js View on Github external
API_VERSION,
	COINBASE;

var INSTANCE_NAME = process.env.INSTANCE_NAME;
var WS_SECRET = process.env.WS_SECRET || "eth-net-stats-has-a-secret";

var PENDING_WORKS = true;
var MAX_BLOCKS_HISTORY = 40;
var UPDATE_INTERVAL = 5000;
var PING_INTERVAL = 3000;
var MINERS_LIMIT = 5;
var MAX_HISTORY_UPDATE = 50;
var MAX_CONNECTION_ATTEMPTS = 50;
var CONNECTION_ATTEMPTS_TIMEOUT = 1000;

Socket = Primus.createSocket({
	transformer: 'websockets',
	pathname: '/api',
	timeout: 120000,
	strategy: 'disconnect,online,timeout',
	reconnect: {
		retries: 30
	},
	plugin: {emitter: Emitter, sparkLatency: Latency}
});

if(process.env.NODE_ENV === 'production' && INSTANCE_NAME === "")
{
	console.error("No instance name specified!");
	process.exit(1);
}
github Ezelia / eureca.io / lib / EurecaClient.js View on Github external
var createClient = function (uri, options = {}) {
                options.pathname = options.prefix ? '/' + options.prefix : undefined;
                options.path = options.prefix ? '/' + options.prefix : undefined;
                var socket;
                if (Eureca.Util.isNodejs) {
                    var CSocket = Primus.createSocket(options);
                    socket = new CSocket(uri);
                }
                else {
                    console.log('>>> Ezelia : createClient', uri, options);
                    socket = new Primus(uri, options);
                }
                var client = new Socket(socket);
                return client;
            };
            Eureca.Transport.register('primus', '', createClient, createServer, (v) => v, (v) => v);
github Alethio / ethstats-cli / lib / Server.js View on Github external
import Primus from 'primus';
import primusResponder from 'primus-responder';
import EventEmitter from 'events';
import client from './client/index.js';

const PrimusSocket = Primus.createSocket({
  transformer: 'websockets',
  pathname: '/api',
  parser: 'JSON',
  plugin: {
    responder: primusResponder
  }
});

export default class Server {
  constructor(diContainer) {
    this.pkg = diContainer.pkg;
    this.config = diContainer.config;
    this.configurator = diContainer.configurator;
    this.log = diContainer.logger;
    this.cli = diContainer.cli;
    this.lodash = diContainer.lodash;

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

65 / 100
Full package analysis