Git Product home page Git Product logo

socket.io-redis-emitter's Introduction

The Socket.IO Redis emitter

Build Status NPM version

The @socket.io/redis-emitter package allows you to easily communicate with a group of Socket.IO servers from another Node.js process (server-side).

Emitter diagram

The emitter is also available in other programming languages:

It must be used in conjunction with @socket.io/redis-adapter.

The current version is compatible with both:

  • socket.io-redis@5 (socket.io@2)
  • socket.io-redis@6 (socket.io@3 & socket.io@4)

Table of content

How to use

Installation:

npm i @socket.io/redis-emitter redis

CommonJS

const { Emitter } = require("@socket.io/redis-emitter");
const { createClient } = require("redis"); // not included, needs to be explicitly installed

const redisClient = createClient();

redisClient.connect().then(() => {
  const io = new Emitter(redisClient);

  setInterval(() => {
    io.emit("time", new Date);
  }, 5000);
})

With redis@3, calling connect() is not needed:

const { Emitter } = require("@socket.io/redis-emitter");
const { createClient } = require("redis"); // not included, needs to be explicitly installed

const redisClient = createClient();

const io = new Emitter(redisClient);

setInterval(() => {
  io.emit("time", new Date);
}, 5000);

TypeScript

import { Emitter } from "@socket.io/redis-emitter";
import { createClient } from "redis";

const redisClient = createClient();

redisClient.connect().then(() => {
  const io = new Emitter(redisClient);

  setInterval(() => {
    io.emit("time", new Date);
  }, 5000);
});

With typed events:

import { Emitter } from ".";
import { createClient } from "redis";

interface Events {
  basicEmit: (a: number, b: string, c: number[]) => void;
}

const redisClient = createClient();

redisClient.connect().then(() => {
  const io = new Emitter<Events>(redisClient);

  io.emit("basicEmit", 1, "2", [3]);
});

Emit cheatsheet

const { Emitter } = require("@socket.io/redis-emitter");
const { createClient } = require("redis"); // not included, needs to be explicitly installed

const redisClient = createClient();
const io = new Emitter(redisClient);

// sending to all clients
io.emit(/* ... */);

// sending to all clients in 'room1' room
io.to("room1").emit(/* ... */);

// sending to all clients in 'room1' except those in 'room2'
io.to("room1").except("room2").emit(/* ... */);

// sending to individual socketid (private message)
io.to(socketId).emit(/* ... */);

const nsp = io.of("/admin");

// sending to all clients in 'admin' namespace
nsp.emit(/* ... */);

// sending to all clients in 'admin' namespace and in 'notifications' room
nsp.to("notifications").emit(/* ... */);

Note: acknowledgements are not supported

API

Emitter(client[, opts])

client is a node_redis compatible client that has been initialized with the return_buffers option set to true.

The following options are allowed:

  • key: the name of the key to pub/sub events on as prefix (socket.io)
  • parser: parser to use for encoding messages to Redis (`notepack.io)

Emitter#to(room:String):BroadcastOperator

Emitter#in(room:String):BroadcastOperator

Specifies a specific room that you want to emit to.

Emitter#except(room:String):BroadcastOperator

Specifies a specific room that you want to exclude from broadcasting.

Emitter#of(namespace:String):Emitter

Specifies a specific namespace that you want to emit to.

Emitter#socketsJoin(rooms:String|String[])

Makes the matching socket instances join the specified rooms:

// make all Socket instances join the "room1" room
io.socketsJoin("room1");

// make all Socket instances of the "admin" namespace in the "room1" room join the "room2" room
io.of("/admin").in("room1").socketsJoin("room2");

Emitter#socketsLeave(rooms:String|String[])

Makes the matching socket instances leave the specified rooms:

// make all Socket instances leave the "room1" room
io.socketsLeave("room1");

// make all Socket instances of the "admin" namespace in the "room1" room leave the "room2" room
io.of("/admin").in("room1").socketsLeave("room2");

Emitter#disconnectSockets(close:boolean)

Makes the matching socket instances disconnect:

// make all Socket instances disconnect
io.disconnectSockets();

// make all Socket instances of the "admin" namespace in the "room1" room disconnect
io.of("/admin").in("room1").disconnectSockets();

// this also works with a single socket ID
io.of("/admin").in(theSocketId).disconnectSockets();

Migrating from socket.io-emitter

The package was renamed from socket.io-emitter to @socket.io/redis-emitter in v4, in order to better reflect the relationship with Redis.

To migrate to the new package, you'll need to make sure to provide your own Redis clients, as the package will no longer create Redis clients on behalf of the user.

Before:

const io = require("socket.io-emitter")({ host: "127.0.0.1", port: 6379 });

After:

const { Emitter } = require("@socket.io/redis-emitter");
const { createClient } = require("redis");

const redisClient = createClient();
const io = new Emitter(redisClient);

License

MIT

socket.io-redis-emitter's People

Contributors

darrachequesne avatar davidgatti avatar defunctzombie avatar dependabot[bot] avatar dimitarnestorov avatar ghemingway avatar haridas avatar jvictorsoto avatar masterodin avatar nathanbowser avatar nkzawa avatar papandreou avatar rase- avatar rauchg avatar sam-github avatar sebamarynissen avatar shian15810 avatar tada5hi avatar v4l3r10 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socket.io-redis-emitter's Issues

How can we wait for emit() to finish?

Hi team, we're using this with redis in an AWS lambda function which means we need to close connections and let lambda know we're done as soon as possible so they don't keep charging us.

Using your example code, sometimes we are seeing errors where the PUBLISH command is issued to redis after we've closed the redis connection because your example code is running synchronously.

How can we wait to ensure .emit() is done with redis before we wrap things up? I don't see any ability to assign a callback or use promises, etc.

Just to clarify, we don't need to wait for acknowledgement that the event has been received in other parts of the system, we just need to make sure the event has been sent into redis and that the PUBLISH command has succeeded.

Can several servers use the same redis?

Several servers use the same redis,but db is different.How can one server send to all its clients but not other servers' clients?
I test it.For example,i send message in server A,but server B‘s clients receive this message.Because A and B use the same redis

How to disconnect?

Hi!

Is there any way to disconnect from redis when I'm finish?
i.e:

const ioEmitter = require('socket.io-emitter')

const io = ioEmitter({ host: 'localhost', port: 6379 })
io.emit('test')

// io.close() or something?

this may be useful for cli tools, or in CI

Needs a new release

We need a new release, since there are some of major changes since the last version:

  • support for emitting to namespaces
  • possibility to connect through a unix domain socket
  • bumped has-binary-data

possible EventEmitter memory leak detected

Logs are below:

rtcblue-1 (err): at E:\Go Agent\pipelines\Blue-Build-Deploy-RTCIO-Signaller\node_modules\socket.io\lib\namespace.js:
174:14
rtcblue-1 (err): at _combinedTickCallback (node.js:370:9)
rtcblue-1 (err): at process.tickDomainCallback (node.js:425:11)
rtcblue-1 (err): error: Socket.io (peer) says: disconnected with connection id /#d5TphKlO9tOdVL-FAAAI
rtcblue-1 (err): error: Socket.io (peer) says: disconnected with connection id /#sttO417fZ8X1fZBlAAAH
rtcblue-1 (err): (node) warning: possible EventEmitter memory leak detected. 11 data listeners added. Use emitter.setMax
Listeners() to increase limit.
rtcblue-1 (err): Trace
rtcblue-1 (err): at EventEmitter.addListener (events.js:252:17)
rtcblue-1 (err): at Object.announce.
.board.on [as announce](E:Go AgentpipelinesBlue-Build-Deploy-RTCIO-Signalle
rtargetwebrtcswitchBoardHandlerscall.js:60:15)
rtcblue-1 (err): at doThisWithPeer (E:\Go Agent\pipelines\Blue-Build-Deploy-RTCIO-Signaller\target\webrtc\mainSwitch
.js:40:32)
rtcblue-1 (err): at Namespace. (E:\Go Agent\pipelines\Blue-Build-Deploy-RTCIO-Signaller\target\webrtc\soc
ketHandlers\peer.js:11:9)
rtcblue-1 (err): at emitOne (events.js:90:13)
rtcblue-1 (err): at Namespace.emit (events.js:182:7)
rtcblue-1 (err): at Namespace.emit (E:\Go Agent\pipelines\Blue-Build-Deploy-RTCIO-Signaller\node_modules\socket.io\l
ib\namespace.js:206:10)
rtcblue-1 (err): at E:\Go Agent\pipelines\Blue-Build-Deploy-RTCIO-Signaller\node_modules\socket.io\lib\namespace.js:
174:14
rtcblue-1 (err): at _combinedTickCallback (node.js:370:9)
rtcblue-1 (err): at process._tickDomainCallback (node.js:425:11)
rtcblue-1 (err): error: Socket.io (peer) says: disconnected with connection id /#QqDHc_MsT1dffS0NAAAJ
rtcblue-1 (err): error: Socket.io (peer) says: disconnected with connection id /#BQFBtMezSBtDaPw4AAAL
rtcblue-1 (err): error: Socket.io (peer) says: disconnected with connection id /#9r11P2ZNFBhaACF6AAAK

Can't install this package

Hi,

when trying to installl this package I run into following

15:15 $ npm i socket.io-emmiter --save
npm ERR! Darwin 15.6.0
npm ERR! argv "/usr/local/Cellar/node/6.4.0/bin/node" "/usr/local/bin/npm" "i" "socket.io-emmiter" "--save"
npm ERR! node v6.4.0
npm ERR! npm  v3.10.3
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/socket.io-emmiter
npm ERR! 404
npm ERR! 404  'socket.io-emmiter' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/schovi/work/be/chat-ws/npm-debug.log

For some unknow reason to me, package info in registry is empty https://registry.npmjs.org/socket.io-emmiter

Namespace value mismatch between socker.io and socket.io-emmiter

socker.io configuration:

const io = require('socket.io')(webServer).of('nsp');

When we emit a message to a room it's publish the message in socket.io#/nsp#myRoom# channel.

In other project we initialize socker.io-emitter:

const io = require('socket.io-emitter')({host: redisHost, port: redisPort}).of('nsp')

When we emit a message to a room it's publish the message in socket.io#nsp#myRoom# channel.

The channels are different as / is missed. As the result we don't receive messages from emitter until we change namespace from nsp to /nsp

how it work?

Three questions

this lib how it work?

Redis is required?

Error: Redis connection to 127.0.0.1:12345 failed - connect ECONNREFUSED 127.0.0.1:12345
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:14)

The 127.0.0.1:12345 is socket.io listen port

Why require Redis?

Question: Can Emitter get a list of rooms, or count of connections in a room?

I have a backed server that is processing Data and I need to know if anyone is still in a room before I process the data for that room (no point doing work if no one is listening). I don't really want to have the full Socket.io(+redis) service running since the back-end server cannot receive client http requests / websockets.
Thanks.

I'm Running in Node.js on Heroku.

Cut new release to get rid of npm’s No repo warning

I see that you added a repo field to package.json quite some time ago, so it would be really appreciated if you could push a new version to npm, so that the warning goes away.

Not a high priority issue, of course, it just bugs me :)

Connection timeout

I have var redis = require('socket.io-redis');io.adapter(redis({ host: 'hhhhh', port: xxxx})); which is connecting normally and when i use var emiter = require('socket.io-emitter')({ host: 'hhhhh', port: xxxx }); this got timout error. Both those are in the same file app.js.

Does it support Acknowledgement as in main Socket.io emitter?

I am trying to pass acknowledgement function while emitting to client but it's not working but in socket.io node process it is working file. here is my code below:

io
.to(socketId)
.emit("event", data,function (err,message) {
     console.info(message);
     console.error(err);
});

the callback function is not called and in java client i am gutting ack function null.

why cannot emitter join room?

hi,
in my server process, user send his gps and i broadcast it to room 'position'

socket.on('position',(gps)=>{
io.to('position').emit(someone's gps);
})

and i want to collect all the gps in my emitter process
if i can use:

var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
io.join('position');
io.on('position',(data)=>{
//collect everyone's gps to one object
});

so that, i can broadcast everyone's gps every 5s in room 'gps'
if someone care, he can join room 'gps'
setInterval(function(){
io.to('gps').emit('all position', 'data');
}, 5000);

so, my question is why cannot emitter join room? is there any other better solution?

Emitter.prototype.of should return a new Emitter instance

It would be great to be able to do something like this:

var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
var nspEmitter = io.of('/someNamespace');

... and then be able to use nspEmitter multiple times afterwards to do actions related to that namespace. That would make it behave similarly to the of() function of SocketIO itself: http://socket.io/docs/rooms-and-namespaces/#custom-namespaces

Instead, for socket.io-emitter, the of() function needs to be used before each emit(). This inconsistency between SocketIO and socket.io-emitter leads to some confusion. At the very least, the documentation should state that of() needs to be called before each emit().

Socket.io Compatible Messages? Dispatch/Encoding/Event Wrapper differences

Hi,
I'm attempting to write a processing script that needs to publish socket.io compatible events to redis. I've configured everything the same as my socket.io server but I'm seeing differences in the pubsub events created by socket.io and socket.io-emitter when using redis-cli monitor

Here's a message generated by my Sails application using socket.io:

1406528387.211758 [0 127.0.0.1:55976] "publish" "dispatch" "{"nodeId":1526207527,"args":["/sails_model_shelf_5VDFEDFDFV:update","5:::{\"name\":\"shelf\",\"args\":[{\"verb\":\"updated\",\"data\":{\"owner\":2,\"display_name\":\"Test\",\"shelf_hashid\":\"5VDFEDFDFV\",\"watch_folder\":{\"display\":\"skydrive://Public/BookShelf/\",\"parent_identifier\":\"/Public\",\"identifier\":\"/Public/BookShelf\",\"created_at\":\"2014-07-26T03:48:44.828Z\",\"credential_id\":3233,\"service_type\":\"skydrive\"},\"watch_folder_checked_at\":null,\"status\":\"\",\"storage_container\":\"ss4545d\",\"id\":\"5VDFEDFDFV\",\"createdAt\":\"2014-07-25T01:17:01.000Z\",\"updatedAt\":\"2014-07-27T23:43:14.000Z\"},\"id\":\"5VDFEDFDFV\"}]}",null,[]]}"

Now here's one using socket.io-emitter

1406527016.104451 [0 127.0.0.1:55749] "publish" "dispatch#emitter" "\x92\x83\xa4type\x02\xa4data\x92\xa5shelf\xda\x01\xd0{"verb":"updated","data":{"owner":2,"display_name":"Test","shelf_hashid":"5VDFEDFDFV","watch_folder":{"display":"skydrive://Public/BookShelf/","parent_identifier":"/Public","identifier":"/Public/BookShelf","created_at":"2014-07-26T03:48:44.828Z","credential_id":3233,"service_type":"skydrive"},"watch_folder_checked_at":null,"status":"","storage_container":"ss4545d","id":"5VDFEDFDFV","createdAt":"2014-07-25T01:17:01.000Z","updatedAt":"2014-07-27T23:43:14.000Z"},"id":"5VDFEDFDFV"}\xa3nsp\xa1/\x82\xa5rooms\x91\xbfsails_model_shelf_5VDFEDFDFV:update\xa5flags\x80"

There's three main differences.

  1. Socket.io-emitter is adding a #emitter to the end of the dispatch key that I set.
  2. The socket.io message is correctly JSON encoded (and the payload is double encoded). This is probably due to the json function in socket.broadcast.to(room).json.send(data)
    https://github.com/balderdashy/sails/blob/3c7be331e9d2f6a503ab950ebd23bda2742a8857/lib/hooks/sockets/lib/interpreter/interpret.js#L535-L538 But I can't seem to find a way to correctly json encode in socket.io-emitter.
  3. The payload wrapper is completely different. Socket.io has a nodeid field, args field and is structured differently. (This difference could be due to some missing sails functionality, so I may be able to fix this myself.)

Any help or direction you could provide would be invaluable :)

Compatiblity with Socket 2.x

After upgrading Socket to 2.x (earlier we were on 1.x), the emitted events/messages are not reaching the clients. socket.io-emitter used is the latest release.

"socket.io": "2.0.3"
"socket.io-client": "2.0.3"
"socket.io-emitter": "3.1.0"
"socket.io-redis": "5.1.0"

Is the current version confirmed to be compatible/work with Socket 2.x ? Or any adjustments are needed in code?

Thanks

Emitting to a room while using socket.io-redis

While emitting to a room using io.to(room).emit('message',message.data); in emitter,the event goes to the broadcast of the redis-adapter from Redis.prototype.onmessage and it does not seem to be publishing to the sockets in the room but rather only to the sockets based on the namespace.Does the ability to emit to a room exist? Thank you

Socket.io-emitter and Heroku

The app I have on my local machine can use websockets just fine. I am using a windows machine with socket.io and Redis (but not hiredis).

The application on Heroku can receive websocket events just fine. I can see this in the logs. The problem is when I use socket.io-emitter to emit events back to the client. Basically, nothing happens at all. Nothing shows up in the logs, and there are no errors thrown.

Send message from php server to node.

send message from node socket.io to server

and php server send message to socket.io and node send message to client .

I dont know this is possiable in socket.io

How to authenticate with remote redis instance?

Can't seem to get socket.io-emitter to authenticate..
Error: Ready check failed: NOAUTH Authentication required.

Something like:
require('socket.io-emitter')({ host: 'host.com', port: 4532, pass:'pass' }) would make a lot of sense.. or am I missing something?

Edit: I just noticed the pull request.. Silly me :)

This won't work with socket.io.1.4.5 ??

I just upgraded socket.io to 1.4.5 because there was a memory leak in the 1.3.7 version due to a change in ws. after upgrading emitter is not working as the obj type is being treated as undefined in the socketio server.

Emitting events to the server side of socket.io

How to emit an event to the server side of socket.io ? This library enables to emit an event to the client side of socket.io, but I want to emit an event to the server side of socket.io too.

Sorry for my bad English.

Catch errors

Sometimes we have connection issues with redis. While this is pretty bad for our service it does not really help that the emitter package just crashes when redis has a "timed out" error. This issue here is also related: redis/node-redis#530

I would suggest, that some kind of error handling for this in introduced. Maybe add a callback to the "emit" function or just log.error the redis problems?

How to use this library?

i have run npm install socket.io-emitter --save

and try connect to server :

var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 8081});
setInterval(function(){
  io.emit('time', new Date);
}, 5000);

and showing this error :

image

when i try to install any package,i got problem :

image

this library for client side or server side?

How do I listen for events? Nothing is responding to emitter(s)

I'm setting up an example app, and cannot figure out how to listen for events from socket.io-emitter (or socket.io-php-emitter). Everything seems to be working fine. I have two browsers that connect sucessfully to Socket.IO. The 'connection' event fires, and I can emit from Socket.IO back to the clients.

However, when I try to emit from socket.io-emitter (using the sample code in a separate process), or emit from PHP, I can see the publish events happening in Redis, but nothing happens on the connected clients. Is there anything special I need to do to pass events from socket.io-emitter to clients connected to Socket.IO?

My code is here:

// ===> socketapp.js <===

var server = require('http').Server();
var io = require('socket.io')(server);
var redis = require('socket.io-redis');

io.adapter(redis({ host: '127.0.0.1', port: 6379 }));

io.on('connection', function(socket){
    console.log('client connected'); // Works

    socket.emit('connect','test'); // Works
});

server.listen(3000);

// ===> Client/Browser JavaScript <===

$(function(){
    var socket = io('http://localhost:3000');

    socket.on('connect',function(){
        console.log("Client Connected!"); // Works
    });

    // Listen for events from socket.io-php-emitter
    socket.on('testPHPevent', function(data){
       console.log("Testing PHP Emitter -- " + data); // Nothing
    });

    // Listen for events from socket.io-emitter (running in a separate process)
    socket.on('time', function(data){
        console.log("Time " + data);  // Nothing
    })
});

// ===> socket.io-php-emitter code <===

        $redis = new \Redis();
        $redis->connect('127.0.0.1', '6379');
        $emitter = new SocketIO\Emitter($redis);

        $data = array(
            'thing' => 'test'
        );

        $emitter->emit('testPHPevent', $data);

// * REDIS SUBSCRIBE output (for socket.io-php-emitter)*

127.0.0.1:6379> SUBSCRIBE socket.io#emitter
...
1) "message"
2) "socket.io#emitter"
3) "\x92\x83\xa4type\x02\xa4data\x92\xactestPHPevent\x81\xa5thing\xa4test\xa3nsp\xa1/\x82\xa5rooms\x90\xa5flags\x90"

// ===> socket.io-emitter test application code <===

var io = require('socket.io-emitter')({
    host:'localhost',
    port:'6379'
});
setInterval(function(){
    io.emit('time', new Date);
}, 5000);

// *** REDIS SUBSCRIBE output (for socket.io-emitter) ***

1) "message"
2) "socket.io#emitter"
3) "\x92\x83\xa4type\x02\xa4data\x92\xa4time\xb82014-09-01T18:23:22.612Z\xa3nsp\xa1/\x82\xa5rooms\x90\xa5flags\x80"

Hopefully this is clear. Everything I'm doing here is based of sample code from README files and the Socket.IO website. It just looks like everything is getting "stuck" in Redis.

Also, I tried putting a console.log in the socket.io-redis adapter onmessage function, and it never happened. I'm not sure if this is a problem with socket.io-redis, or socket.io-emitter, or my code.

Any assistance would be appreciated. Thanks.

lose namespace when emit multiple rooms

code:

const rooms = ['room1', 'room2'];
const nsp = io.of('/some namespace');
for (let room of rooms) {
  nsp.to(room).emit('message', 'test');
}

the namespace of the second room will be lost

Maximum callstack size exceeded

Hello, in new version with msgpack-lite i have following issues...
But im not sure, should i post them here or to msgpack...
RangeError: Maximum call stack size exceeded at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:26 at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native)
and
RangeError: Maximum call stack size exceeded Something bad happened: RangeError: Maximum call stack size exceeded at EncodeBuffer.reserve (I:\repos\wt-server2\node_modules\msgpack-lite\lib\flex-buffer.js:109:19) at EncodeBuffer.reserve (I:\repos\wt-server2\node_modules\msgpack-lite\lib\flex-buffer.js:109:19) at Array.<anonymous> (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-uint8.js:11:26) at Array.<anonymous> (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-uint8.js:11:26) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:234:16) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:234:16) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at Array.forEach (native) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at Array.forEach (native) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) at Array.forEach (native) at obj_to_map (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237:10) at object (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:165:5) at encode (I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-core.js:23:5) at I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:239:7 at Array.forEach (native) I:\repos\wt-server2\node_modules\msgpack-lite\lib\write-type.js:237 keys.forEach(function(key) {

about redis and emitter?Missing redis 'host'

In my app.js .
first I

var Server = require('socket.io');
var io = new Server(30134);
var redis = require('socket.io-redis');

io.adapter(redis({ host: '127.0.0.1', port: 6379 }));

and then

app.get("/ts", function (req, res) {
var io = require('socket.io-emitter')();
// setInterval(function(){
// io.emit('time', new Date);
// }, 5000);

//console.log(chat);    

});

The program get me an errror

mossing redis 'host'
at new Emitter \node_modules\socket.io-emiiter\index.js 53:43

Cannot capture room event using the standard io.sockets.in("room").on("event",function(){})

I am using this emitter alongside the redis socket.io adapter in order to scale my servers, the thing is that I am not able to intercept events from serverA in serverB, the event goes through to the clients of serverB but cant intercept it using the standard :
io.sockets.in("room").on("event",function(){})

any idea why? is there something like emitter.in("room").on("event",handler) ?

thank you! 👍

Emit Array Buffer does not send as Binary.

I'm trying to send an ArrayBuffer as binary to the client, my code worked when using the normal socket.io but Emitter sends the Array Buffer as JSON which is much less efficient bandwidth wise.
Shouldn't Emit work the same for socket.io as socket.io-emiter?

My socket.io-emitter code

//-----------my emitter code-------------//
    var nsp = io.of('/nsp');
    nsp.binaryType = 'arraybuffer';
//other stuff
    var send = new Float32Array(data);
    nsp.to(clientKey).emit("DataSend", send.buffer);

My old socket.io code

//-----------normal socket code-------------//
    var socket = io.of('/nsp');
    socket .binaryType = 'arraybuffer';
//other stuff
    var send = new Float32Array(data);
    socket.emit('DataSend', send.buffer);

How do you implement and use this library?

I've been trying for few days now to make this library work with my sockets in order to make an API call to an endpoint and from that endpoint emit a message to a certain user, I have to do it this way because I need to give the API endpoint to some service to use it as a webhook and emit the result to the user (So basically the user logs in with an outside service and performs an action in that service through my app, and once that action has been fulfilled by that other service I get an update to my API endpoint and from that endpoint I want to emit the message to the user to let them know about that and the part of emitting the message from the API endpoint process to the user's socket is what's causing me problems)

When I try to run this server it immediately gives me the following error:

events.js:174
throw er; // Unhandled 'error' event
^

Error: Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)

Here's my working code (This code works but it doesn't have the socket.io-emitter library so I can't emit a message to the socket from a non-socket process)

var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);

io.on("connection", (socket) => {
    console.log("User connected: ", socket.id);
    io.to(socket.id).emit("new_message", {id: "999", msg: "Welcome back, your Id is " + socket.id});
})

//here I want to emit a message to a user by the URL params
app.get("/send/:id/:message", (request, result) => {
    result.send("Id = " + request.params.id)
})

const port = 3001;
http.listen(port, () => {
    console.log("Listening to port " + port);
});

And this is how I tried to implement socket.io-emitter into the above code:

  1. Add the following code to the top of the script:
const redis = require('socket.io-redis');
io.adapter(redis('//localhost:6379'));
  1. Add the following code inside the app.get("/send/:id/:message"....) function:
    const ioEmitter = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
    ioEmitter.to(request.params.id).emit({ id: "999", msg: request.params.message });
  1. Here are the relevant depends I installed in this project while trying to make this library work, just so that you can see if I missed to install some libraries, or if there are some that collide:
"ioredis": "^4.14.1",
"redis": "^2.8.0",
"socket.io": "^2.3.0",
"socket.io-emitter": "^3.1.1",
"socket.io-redis": "^5.2.0"

I'd appreciate any attempt to help :)

Flags is not work

var io = require('socket.io-emitter')({ host: '127.0.0.1', port: 6379 });
io.broadcast.emit('event', 'data');

the broadcast flag is ignored, same with the other flags.

Examples

Can you add some examples using 2 or more io emitters?

Emitting to namespace not working

Hello

Emitting to namespace is not working, I think it is because you are deleting the object on Line 120:
delete this._flags.nsp;

Is there a reason for this? This deletes the reference in this case also the stored value.

regards

Patrick

adapter issue

I get below error when i try to do emit. I am connecting with same redit on which i am attaching adapter.

  this.encoder.encode(packet, function(encodedPackets) {
              ^

TypeError: Cannot read property 'encode' of undefined
    at Redis.Adapter.broadcast (C:\Work\node_modules\socket.io-redis\node_modules\socket.io-adapter\index.js:136:15)
    at Redis.broadcast (C:\Work\node_modules\socket.io-redis\index.js:416:33)
    at Redis.onmessage (C:\Work\node_modules\socket.io-redis\index.js:165:20)
    at emitThree (events.js:116:13)
    at RedisClient.emit (events.js:194:7)
    at return_pub_sub (C:\Work\node_modules\redis\index.js:796:18)
    at RedisClient.return_reply (C:\Work\node_modules\redis\index.js:833:9)
    at JavascriptRedisParser.returnReply (C:\Work\node_modules\redis\index.js:192:18)
    at JavascriptRedisParser.execute (C:\Work\node_modules\redis-parser\lib\parser.js:574:12)
    at Socket.<anonymous> (C:\Work\node_modules\redis\index.js:274:27)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at Socket.Readable.push (_stream_readable.js:134:10)
    at TCP.onread (net.js:547:20)```

Cannot send callbacks when emitting to single socket

Running Heroku with multiple dynos, and using socket.io-emitter with socket.io-redis.

So far, I am able to emit events to specific connected clients using emitter.to(socketId).emit(...).

However, I'm trying to do emitter.to(socketId).emit('event', function(){...}), but the callback function is never sent to the client. Any other type of argument is successfully sent, but callback functions show up as undefined.

Is this by design? If so, is there any chance of this being introduced in a future update? I'm relying on callbacks quite a bit and am trying to avoid abandoning them.

Socket emit with ack function

Hello. I can't make an emit with ack function. I would like to send information from client to server, and then, a server will need to reply. Can you help me how to make that, please? Is that appropriate way, if so, how to make it work? Because now it doesn't!
Server

const electron = require('electron');
const {app, BrowserWindow} = electron;

app.on('ready', () => {
  let win = new BrowserWindow({width:800, height: 600})
  win.loadURL(`file://${__dirname}/index.html`)
  win.webContents.openDevTools()
})

var server = require('http').createServer();
var io = require('socket.io')(server);

io.on('connection', function(client){
  console.log('Socket connection established');

  io.on("signIn", (bid, text) => {
      domain('Root!');

  });
});



server.listen(3000);

Client


var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
  console.log('Client connected');

  socket.emit('signIn', 'coffee', (data) => {
    console.log(data); // data will be 'Pizza'
  });


});

Thank you!

Constructor throws error

var io = require('socket.io-emitter')({ host: 'localhost', port: 6379});

throws

Error: Missing redis `port`

This example is sourced from the readme and is non-functional. The library also does not support socket.io-redis. This was encountered using socket.io 2.0.1 on Windows 10

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.