Git Product home page Git Product logo

koa-websocket's People

Contributors

cymen avatar dependabot-preview[bot] avatar dependabot[bot] avatar kudos avatar marvinhagemeister avatar stripedpajamas avatar tangxinfa avatar teawithfruit avatar zdila 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

koa-websocket's Issues

`ws` dep compilation error on iojs-v3.2.0

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.

can't use koa-route

node v4.1
koa 1.1.2
koa-route 2.4.2

websocket can connected , but can't send the message

Room management

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.

Close websocket connection?

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.

does not work with [email protected]

[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

Storing Connections?

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?

Allowing additional hooks to server on connection

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.

client example

Can you provide an example client that makes websocket calls to this?

I'm not sure how the routes effect the client side.

example doesn't work

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 :(

wss:// not worked (

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?

It's really nice lib , but 1 question

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

Error: Cannot find module '../'

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)
    ...

example doesn't work with Babel

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

How can I prevent the upgrade?

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?

How can I access session ?

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

How to add a '404' handler?

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?

Access to the WebSocketServer?

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?

no session

The session from koa-generic-session etc doesn't exist on the websocket side

Using the socket variable from "var socket = websockify(app);" koa example?

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);

How to create https server and support websocket or wss use koa2?

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

Does not play well with koa-router

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?

how long will this.websocket alive

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)

Update ws package

The ws package's latest version is 5.1.1. It would we great if it was updated to the latest.

How can I get open event in middleware

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?

Doesn't work on KOA v2

I tried to run the example in koa v2 with the new router but even with koa-convert, it just simple ignores the websocket.

koa2?

Any plans to convert this over to support koa2 and koa-router?

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.