kudos / koa-websocket Goto Github PK
View Code? Open in Web Editor NEWLight wrapper around Koa providing a websocket middleware handler that is koa-route compatible.
License: MIT License
Light wrapper around Koa providing a websocket middleware handler that is koa-route compatible.
License: MIT License
I can't handle the websocket.on('error') call back function
I test this lib , and I can't handle this event , but the close event is ok
Currently it works great with koa-route, but if I add query string in url, it cannot recognize it anymore.
Hi,
are you planning to bump version of ws
dependecy to allow compilation under iojs v3.2.0?
I have compilation problems right now.
Everything works fine with ws v0.8.0
.
Thank you,
O.
node v4.1
koa 1.1.2
koa-route 2.4.2
websocket can connected , but can't send the message
Hi,
I can't find any code in sources nor attribute in ctx.websocket object when logging it in the console related to room management, how to broadcast messages to listed sockets only ?
There's nothing in your example.
Thanks in advance.
How would you properly close a websocket connection? Basically what I am trying to do is check if correct query string parameters are not present then I close the connection.
Here's what I am trying to do right now.
app.ws.use(route.get('/ws', (ctx) => {
const { foo, bar } = ctx.query
if (!foo && !bar) {
ctx.websocket.close(1000, 'Wrong or missing parameters')
ctx.websocket.terminate()
return
}
}))
I am not really sure if this is correct because I keep on getting socket hang up
messages and if I remove the return
everything after the if statement still gets executed. I also tried using onclose
event on the client but it never triggers.
News broadcast, how to do?
[email protected] is the new koa2 router.
The example for koa-router only works with 5.x. I've created an example. If you switch between 7.x and 5.x you can see it will stop working on 7.x
//index.js
require("babel-register");
require("./app.js");
//.babelrc
{
"presets": ["es2015-node5"],
"plugins": [
"transform-async-to-generator",
"syntax-async-functions"
]
}
//app.js
var koa = require('koa');
var websockify = require('koa-websocket');
var router = require('koa-router');
var app = new koa();
var api = router();
var socket = websockify(app);
api.get('/*', function* (next) {
const ctx = this;
ctx.websocket.send('Hello World');
ctx.websocket.on('message', function(message) {
console.log(message);
});
});
app.ws.use(api.routes()).use(api.allowedMethods());
app.listen(3000);
Start with node ./index.js
I cant using broadcast API from here. Any one know how to use brodcast to send message to all clients connected ?
Hi,
I'm trying to differentiate between the clients and having a bit of an issue. The method .onopen
doesn't really provide the necessary callbacks in the parameters to store the connection.
I've also tried doing, websocket.on('connection/open', (open)=>{...})
and still haven't had any luck.
Any suggestions on how to approach storing the (websocket) client information when the websocket connection opens?
KoaWebSocketServer.prototype.onConnection = function onConnection(socket, req) {
};
there is no head .
It seems like the connection
event is not exposed, I can't access it. For example, I want to do:
ctx.websocket.on('connection', function(ws, req){
console.log("connected");
)}
but this doesn't seem to work.
ws is now up to version 6.0, but koa-websocket still depends on 5.2.
Can you provide an example client that makes websocket calls to this?
I'm not sure how the routes effect the client side.
const koa = require('koa');
const websockify = require('koa-websocket');
const router = require('koa-router');
const app = new koa();
const api = router();
const socket = websockify(app);
api.get('/*', function* (next) {
this.websocket.send('Hello World');
this.websocket.on('message', function(message) {
console.log(message);
});
});
app.ws.use(api.routes()).use(api.allowedMethods());
app.listen(3000);
When I try to debug with wscat -c ws://localhost:3000
nothing happens :(
const httpsOptions = {
key: fs.readFileSync('keys/server.key'),
cert: fs.readFileSync('keys/server.crt'),
};
const app = websockify(new Koa(), { port: WS_PORT }, httpsOptions);
and if i connect to WS_PORT from WebSocket client via ws://localhost:WS_PORT that's ok, but if I connect via wss://localhost:WS_PORT i get this error:
Connect Error: Error: write EPROTO 4528641472:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:252:
what could it be?
Unable to receive any message from client
Is the project still under maintenance?
Can you give a brief explanation in the readme.md file, thank you.
I don't know how to manage my clients
any example for manage client ? like I wanna notice 1 client some message , I wanna server push to client , and I wirte some code , it's little stupid , want better solution
this.websocket.send('waiting for verify data');
//message format : cmd|arg
//need save this.websocket here
var socket = this.websocket
this.websocket.on('message', function(message) {
var vec_str = message.split('|');
var cmd = vec_str[0];
var arg = vec_str[1];
console.log(cmd,arg);
var argobj = JSON.parse(arg);
console.log(argobj);
switch(cmd){
case 'verify':{
var username = argobj.user;
var password = argobj.password;
//test code
var exampleShop = shopData[0];
var exampleShopObj = exampleShop.toObject();
exampleShopObj.websocket = socket ;
onlineStoreManager.addStore(exampleShop._id , exampleShopObj);
onlineStoreManager.sendMessage(exampleShop._id,"login sucess");
}
break;
}
});
first time use websocket , I don't know how to manage client
from your example
const koa = require('koa'), route = require('koa-route'), websockify = require('../');
returns error
Error: Cannot find module '../' at Function.Module._resolveFilename (module.js:336:15) at Function.Module._load (module.js:278:25) ...
var koa = require('koa');
var websockify = require('koa-websocket');
var router = require('koa-router');
var app = new koa();
var api = router();
var socket = websockify(app);
api.get('/test', async (ctx, next) => {
ctx.websocket.send('Hello World');
const message = await ctx.websocket.on('message');
console.log(message);
});
app.ws.use(api.routes()).use(api.allowedMethods());
app.listen(3000);
I'm connecting to ws://localhost:3000/test
via ARC (advanced rest client) and it connects and sends a message, but I the callback never fires for api.get('/*', cb)
I also tried using async and still doesn't fire the callback.
api.get('/test', async (ctx, next) => {
ctx.websocket.send('Hello World');
ctx.websocket.on('message', function(message) {
console.log(message);
});
});
I've narrowed it down to an issue with using Babel. The default code works fine as in the example...but I have to get this work with babel/async
I'm trying to do a basic auth middleware that would prevent upgrading the HTTP request if there is some missing token in headers.
Right now this library "Swallows" all the errors. I see it emitting them in debug, but I can't handle them as part of my koa error handler.
How can I prevent the upgrade, or throw an error?
ws
version 1.0.1 fixed a denial of service vulnerability. This dependency should be updated as soon as possible
Can anyone please tell me how can I access session ?
import session from 'koa-session';
const sessionParser: any = session(
{
key: process.env.SESSION_SECRET || '',
maxAge: 1000 * 86400,
overwrite: true,
rolling: true,
renew: true,
httpOnly: true,
signed: true,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production',
},
app,
);
app.use(sessionParser);
app.ws.use(sessionParser);
Not getting any session
I mounted WebSockets into my application using koa-websocket@4 and koa-router@7 under the routes /xyz/...
. As long as only try to to connect with my WebSocket client to an implemented route, everything is fine. But when I try e.g. to connect to /xyz/notimplemented
the client simply hangs.
So I thought "OK, I need to add a '404' middleware for WebSockets too" and started off with the standard Koa approach. But that just causes nasty back traces being logged on the server side (due to the catch( debug() )
clause in the 'connection'
event handler) and leaves the client hanging:
app.ws.use(router.routes())
.use(router.allowedMethods());
app.ws.use(ctx => {
ctx.throw(404, `route '${ctx.url}' not implemented`);
});
After a lot of head-scratching and trial & error I came up with the following, which makes sure the client exits nicely (the 4004 is not a typo) and reduces the log entry on the server side to one line:
app.ws.use(ctx => {
ctx.websocket.close(4004, `ERROR: route '${ctx.url}' is not implemented`);
return Promise.reject(`route '${ctx.url}' is not implemented`);
});
If I comment out the return Promise.reject(...);
line in the code above, then the server log shows:
koa:websockets TypeError: Cannot read property 'statusCode' of undefined
koa:websockets at Object.get status [as status] (.../node_modules/koa/lib/response.js:72:21)
koa:websockets at Object.status (.../node_modules/delegates/index.js:72:24)
koa:websockets at .../node_modules/koa-router/lib/router.js:409:16
koa:websockets at <anonymous>
koa:websockets at process._tickCallback (internal/process/next_tick.js:188:7) +4ms
which as far as I can tell is caused by the koa-websocket context being incomplete (it is missing a response object) and Koa barfs on it when the context is passed back up to it :-/
I can live with my solution, but I'm wondering if I'm missing something or should this be considered a bug/missing feature in koa-websocket?
Having trouble trying to access the instantiated WebSocketServer in order to loop over all clients and broadcast, similarly to the example in the ws
documentation:
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
client.send(data);
});
};
How would you gain access to the clients list?
The session from koa-generic-session etc doesn't exist on the websocket side
From the koa router example, what's the socket variable used for?
var koa = require('koa');
var websockify = require('koa-websocket');
var router = require('koa-router');
var app = koa();
var api = router();
**var socket = websockify(app);**
api.get('/*', function* (next) {
this.websocket.send('Hello World');
this.websocket.on('message', function(message) {
console.log(message);
});
});
app.ws.use(api.routes()).use(api.allowedMethods());
app.listen(3000);
Create https server:
const Koa = require('koa');
const app = new Koa();
const options = {
key: fs.readFileSync('./ssl/private.pem', 'utf8'),
cert: fs.readFileSync('./ssl/20180303.crt', 'utf8')
};
https.createServer(options, app.callback()).listen(443);
Then how to make ws or wss work with https? Please @kudos
When I mount the WS endpoint with koa-router I'm getting this exception when I'm trying to establish a WS connection with a proper client:
TypeError: Middleware must be composed of functions!
at compose (/graphql-dataloader-boilerplate/node_modules/koa-compose/index.js:25:41)
at KoaWebSocketServer.onConnection (/graphql-dataloader-boilerplate/node_modules/koa-websocket/index.js:27:22)
at emitOne (events.js:96:13)
at WebSocketServer.emit (events.js:188:7)
at /graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:91:14
at completeHybiUpgrade2 (/graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:284:5)
at completeHybiUpgrade1 (/graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:309:13)
at WebSocketServer.handleHybiUpgrade (/graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:337:3)
at WebSocketServer.handleUpgrade (/graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:173:26)
at Server.WebSocketServer._onServerUpgrade (/graphql-dataloader-boilerplate/node_modules/ws/lib/WebSocketServer.js:89:12)
at emitThree (events.js:116:13)
at Server.emit (events.js:194:7)
at onParserExecuteCommon (_http_server.js:409:14)
at HTTPParser.onParserExecute (_http_server.js:377:5)
The integration is very basic like so:
app.ws.use(router.all('/ws', function(ctx) {
ctx.websocket.on('message', (message) => {
console.log(message);
});
}));
app
.use(router.routes())
.use(router.allowedMethods());
Everything is koa 2.0.0 stuff.
I debuged it and the reason is that koa-compose complains that the router middleware is not a function but an object. Any idea what is to blame for that?
I save this.websocket
on message like this
var some_container = {};
this.websocket.on('message', function(message) {
some_container.websocket = this.websocket
}.bind(this));
and I want use this websocket for sometime
then I call like this
some_container.websocket.send("test str");
then will show some error like
Error: not opened
at WebSocket.send (/data/order-server-admin/node_modules/koa-websocket/node_modules/ws/lib/WebSocket.js:218:16)
at Object.onlineStoreManager.noticeStoreOrder (/data/order-server-admin/lib/middleware/online_store_manager.js:75:13)
at Object.PickingController.startPicking (/data/order-server-admin/lib/controllers/picking_controller.js:344:23)
at GeneratorFunctionPrototype.next (native)
at onFulfilled (/data/order-server-admin/node_modules/koa/node_modules/co/index.js:64:19)
at in_the_handler (/data/order-server-admin/node_modules/mongoose/node_modules/mpromise/lib/promise.js:237:18)
at process._tickCallback (node.js:355:11)
The ws package's latest version is 5.1.1. It would we great if it was updated to the latest.
I try to get open
event in my log4js middleware, but emit seem like before the middleware listener, I just can get message
close
error
events in middleware
So how can I get it?
I tried to run the example in koa v2 with the new router but even with koa-convert, it just simple ignores the websocket.
It's a bit confusing that npm is on 2.0.0 but github on 1.1.0
Any plans to convert this over to support koa2 and koa-router?
As of this commit, npm
is now a dependency of koa-websocket
.
I don't believe this was intentional and now it's causing all installations of this package to also include npm
itself.
I would like to pass an options object to the new WebSocketServer()
call.
As far as I see, this is impossible currently. I think it needs to be enabled here by a second param:
https://github.com/kudos/koa-websocket/blob/next/index.js#L15
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.