Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'rpc-websockets' 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.
return new Promise((resolve, reject) => {
this.address = this.node.wsAddress
// For testing atom queueing during connection issues
// if (Math.random() > 0.1) {
// this.address += 'garbage'
// }
logger.info(`Connecting to ${this.address}`)
this._socket = new Client(this.address, { reconnect: false })
this._socket.on('close', this._onClosed)
this._socket.on('error', error => {
logger.error(error)
reject(error)
})
setTimeout(() => {
if (!this._socket.ready) {
logger.debug('Socket timeout')
this._socket.close()
this.emit('closed')
reject('Timeout')
}
}, 5000)
constructor(public host: string, private ecdsaPrivateKey?: string) {
// Simply create socket
this._wsRPC = new WSClient(host)
// If no privakey passed generate a random wallet
this._wallet = ecdsaPrivateKey ? new Wallet(ecdsaPrivateKey) : Wallet.createRandom()
// Emits new messages to the provider handler above (Web3)
this._wsRPC.once('open', () => {
;((this._wsRPC as any).socket as EventEmitter).on(
'message',
this._onWebSocketMessage.bind(this)
)
;((this._wsRPC as any).socket as WebSocket).onclose = () => {
this.reset()
}
})
// Prepare LoomProvider2 default methods
const connectedPromise = new Promise((resolve) => {
log.info(
`Connecting to Dart Observatory: ${dartObservatoryURL}`,
);
const socket = new Client(dartObservatoryURL);
const removeListenerAndResolve = (r: NullableWebSocketDummy) => {
socket.removeListener(`error`, onErrorListener);
socket.removeListener(`timeout`, onTimeoutListener);
socket.removeListener(`open`, onOpenListener);
resolve(r);
};
// Add an 'error' event handler for the client socket
const onErrorListener = (ex) => {
log.error(ex);
log.error(
`Check Dart Observatory URI ${dartObservatoryURL}`,
);
removeListenerAndResolve(null);
};
return new Promise((resolve, reject) => {
// This is an independant websocket because 'getRemotePublicKey' is a static method
const socket = new Client(`ws://${host}:${port}`)
socket.on('open', () => {
socket.call('get_public_key', {
token,
}).then((response) => {
resolve(response.data)
}).catch((error) => {
reject(error)
}).finally(() => {
socket.close()
})
})
})
}
constructor (backendVM, opts={}) {
// setup the WebSocket server
this.backendVM = backendVM
this.server = new WebSocketServer({
port: opts.port || DEFAULT_PORT
})
this.isReadyPromise = new Promise((resolve, reject) => {
this.server.on('listening', resolve)
this.server.on('error', reject)
})
// establish the method handlers
this.registerCommands()
this.callQueue = [] // backlog of RPC requests
this.activeCall = null // call currently being processed
}
listenWs: ({ host, port }) => {
const wsServer = new WsJsonRpcServer({
port: port || 8646,
host: host || 'localhost',
});
// register an RPC method
Object.keys(nodeApi).forEach(key => {
wsServer.register(key.toString(), withParams(nodeApi[key]));
});
return new Promise(resolve => {
wsServer.on('listening', () => {
return resolve({
address: wsServer.wss.options.host,
port: wsServer.wss.options.port,
});
});
const WebSocket = require('rpc-websockets').Client;
const URL = 'ws://0.0.0.0:8080/v1';
const ws = new WebSocket(URL);
ws.on('open', function () {
ws.call('getblocks', {limit: 10, offset: '0'})
.then(function(result) {
console.log('getblocks:', result);
});
ws.close();
});
private getSocketConnection(): Client {
this.socket = new Client(this.remoteUrl)
this.socket.on('error', (error) => logger.error(error))
this.socket.on('close', () => logger.info('Socket closed'))
return this.socket
}
return new Promise((resolve, reject) => {
const socket = new Client(`ws://${host}:${port}`)
socket.on('open', () => resolve(true))
setTimeout(() => {
if (socket && socket.ready) {
socket.close()
resolve(true)
} else {
socket.close()
resolve(false)
}
}, 2000)
})
}
connTo = async (n, node) => {
const client = new Client(`${node.addr}?token=${node.token}`)
client.on('open', async () => {
this.setState(p => ({conns: {...p.conns, [n]: client}}))
setInterval(() => this.updateInfo(n), 1333)
})
}