Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'primus' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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}
}
// @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', {});
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);
});
}
// 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: []
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;
}
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();
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);
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()
}
/* 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) {
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();
};