Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ctx.socket.emit does not work from app.use middleware #19

Open
0cv opened this issue Jun 19, 2016 · 2 comments
Open

ctx.socket.emit does not work from app.use middleware #19

0cv opened this issue Jun 19, 2016 · 2 comments

Comments

@0cv
Copy link

0cv commented Jun 19, 2016

I'm trying to integrate socket.io into existing routes/middleware but when doing ctx.socket.emit from the standard Koa middleware, the client does not receive the message. I must also say that ctx.socket.id is undefined, even so ctx.socket isn't. Is it something not supported, or am I doing anything wrong?

Explained differently, this is what I'm trying to do:
1- Client starts an Ajax request (POST/GET/...)
2- Koa handles the request and answers in a regular way
3- Additionally this triggers something on the middleware so that the server send messages to the client, but this is where this does not work.

I'm using Koa 2, Koa-Router 7, if that's any relevant.

@mattstyles
Copy link
Owner

mattstyles commented Jul 6, 2016

The ctx.socket you're seeing in the Koa middleware is not connected to web sockets, its to do with Koa itself.

koa-socket tries to leave koa alone, rather than add functionality specifically to koa it works alongside, but shares the same server for convenience. The only things that the attach method does are to share the server and to attach the io instance/s directly to your Koa application.

As the socket.io instance is attached to the Koa instance you can access some global io methods, such as broadcast, from the app instance but in order to emit to a specific connection you'd have to add some functionality to your code to add the connection id when you hit routes, that way you can emit to a specific connection (pretty sure socket.io allows this). This requires that you pass through your connection id when you hit routes from the client, otherwise Koa has no way to know which WS connection is associated with the client hitting the route.

@plh97
Copy link

plh97 commented Nov 24, 2017

hello ,would you answer my issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants