Code Monkey home page Code Monkey logo

adonis-websocket's People

Contributors

greenkeeper[bot] avatar romainlanz avatar thetutlage 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

Watchers

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

adonis-websocket's Issues

the slash (/) problem on socket path

I have found a small bug on adonis Ws ,
If I add / on end of path in request , Ws server will returns "400 bad request" error and unfortunately most of client library add '/' at end of path.(Ex. most of android ws client libs and socket.io lib and ...) I know that adonis has official Js library but sometimes we need to connect to a Ws from android or ios app.

I found it using telnet let see an example:
Our websocket address is 127.0.0.1:3001/socket (path : 'socket')
and the request is:
GET /socket HTTP/1.1 Host: 127.0.0.1:3001 Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Origin: http://localhost:63342 Sec-WebSocket-Version: 13 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,fa;q=0.8,ar;q=0.7 Cookie: _ga=GA1.1.2121443454.1510749600; csrftoken=r3Dc2FqBbBEbxNyreXRS3WT8C7QYGkYq8rVEbBL7xFOpS44upjvPeHFkuD5P12Dv Sec-WebSocket-Key: IzktWUEMLXAj5nr91pVXAg== Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

at response we get:

`HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 0ysRtfQC1JRuk7XCjVX1uUx9XwI=

?~?{"t":0,"d":{"connId":"cjj7udobh0000rirms57n3lds","serverInterval":30000,"serverAttempts":3,"clientInterval":25000,"clientAttempts":3}}
`

but if we add an slash ('/') at end of path:

GET /socket/ HTTP/1.1 Host: 127.0.0.1:3001 Connection: Upgrade Pragma: no-cache Cache-Control: no-cache Upgrade: websocket Origin: http://localhost:63342 Sec-WebSocket-Version: 13 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,fa;q=0.8,ar;q=0.7 Cookie: _ga=GA1.1.2121443454.1510749600; csrftoken=r3Dc2FqBbBEbxNyreXRS3WT8C7QYGkYq8rVEbBL7xFOpS44upjvPeHFkuD5P12Dv Sec-WebSocket-Key: IzktWUEMLXAj5nr91pVXAg== Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

the response will be:

`HTTP/1.1 400 Bad Request
Connection: close
Content-type: text/html
Content-Length: 11

Bad Request`

I think it is better to ignore slash . Currently I putted a slash at end of the path is config/socket.js but I think it is not a good solution.

Thanks for help,
Kind Regards

Get Socket By User ID and Emit

How do I get a list of sockets without pulling them as the pull function leads to untracking? Just want to get a list of sockets by user id and emit to those sockets.

Connections from SocketIO?

Just starting out with Adonis (I've used Laravel for a good many years) and I'm liking what I am seeing so far.

I am trying to integrate Adonis into an existing project that already has a subsystem (written in python) that communicates via SocketIO.

Can this provider accept connections generated via SocketIO? And if so, how can it be achieved.

Thank you in advance!

Add event ack functionality

Why this feature is required (specific use-cases will be appreciated)?

I would like to use websocket connection to emit event and get the result of it - it is more like request and response flow. This functionality is implemented in socket.io, sails.io, etc. It is a nice feature when you want to get rid of AJAX requests for resource CRUD in SPA and pass all data through websocket. Socket.io implementation example:

// The third "ack" argument is optional and will be called with the client's answer.
socket.emit('hello', 'world', (answer) => {
  console.log(answer) // Hi!
})

// The client code
client.on('hello', (name, ack) => {
  ack('Hi!')
})

Have you tried any other work arounds?

This kind of feature is not easily implemented as addon package, because the core functionality is required on Socket and Connection classes as well as new packet type.

Are you willing to work on it with little guidance?

Sure. Just need your approval.

Proposed API

Update current server API as follows. ~~~emit method already has the ack parameter which recieves the error when packet is not sent, so add another callback with name responseAck~~~

socket.emit('hello', 'world', (err) => {
  if (err) {
    return console.log('Packet sending error: ', err)
  }
  console.log('Packet sent!')
}, (data) => {
  console.log(data) // Hi!
})
```javascript
socket.emit('hello', 'world', (data) => {
  console.log(data)
})
```
For convenience add the promisified version to server and client of this method  with `send`, `request`, `emitWithAck`, `emitWithReply` or other name. **Another option would be just let `emit` methods untouched and implement just new Promise only  `send` methods**
```javascript
const data = await socket.send('hello', 'world')
```

And for returning the response we can only return the response data from event callback:
```javascript
socket.on('hello', (name) => {
  return 'Hi!'
})
```

## Proposed changes
- adonis-websocket-packet
  - add new packet type `ACK` with code 10
  - add optional data property `id` to packet with type `EVENT`, which presence means that `ACK` response packet is expected with the same `topic` and `id`
  - add method `ackPacket` with arguments `(topic, id, data)`
  - add method `isValidAckPacket`, which will check presence of `topic` and `id` props
- adonis-websocket
  - add new properties `this._acks = new Map()` and `this._nextAckId = 0` to `Socket` class
  - add method `Socket.send(event, data)` which wil return Promise.  Get and increment `this._nextAckId` and save resolve callback to `this._acks` map under given ID. Next generate event packet and attach this ID.
  - update `socket.serverMessage` to return a promise with all resolved responses from event callbacks
  - update `Connection._processEvent` to check if packet has `id` (ack is required) and send an `ACK` packet from first resolved response
  - add handling for `ACK` packet in `Connection._handleMessage` which will call `serverAck` method on subscription
  - add `Socket.serverAck` method, which will check if given ack ID exists in map. If so it will call the callback passing recieved data
- adonis-websocket-client
  - nearly all the changes are the same as for server above

For those who cant get optional auth working

I'm just here to help

wsKernel.js

const globalMiddleware = [
  'Adonis/Middleware/Session',
  'Adonis/Middleware/AuthInit',
]

ChatController.js

class ChatController {
  constructor({
    socket,
    request,
    auth
  }) {
    this.socket = socket
    this.request = request
    this.auth = auth
  }

  ongetMessages(message) {
    console.log(this.auth.user)
  }
}

How can I get current logged in user details in controller?

I am trying to get the current user from the socket controller.

Trying to get it like this
`constructor ({ socket, request , auth, session}) {
this.socket = socket
this.request = request
this.auth=auth

}
async onClose (data) {
const user = await this.auth.user
console.log(user) // it gives null
}`

Also tried to get some values from session. Sessions works in all controller except here.
Any ways I can get the user id from here?

Many thanks.

wsServer is not a function

I have:

  1. Installed the websocket package with adonis install @adonisjs/websocket --yarn
  2. Added '@adonisjs/websocket/providers/WsProvider' to providers
  3. Added .wsServer() to the bootstrap chain (after new Ignitor(require('@adonisjs/fold')).appRoot(__dirname))

When trying to start the server i get:

TypeError: (intermediate value).appRoot(...).wsServer is not a function

Am I doing something wrong? I am using adonuxt if that makes a difference.

Automated websocket testing

Hey there,
we've started adding websockets into our project a few days ago and I really enjoy using it. The API turned out to be great and being able to have middleware is amazing.

Our websocket use case is mostly very unidirectional from Server to Client. Let me give you an example:

  1. User A sends a RESTful request to the Server
  2. Server persists some things into the database and performs other actions.
  3. Server then needs to notify Users B, C that something has changed.

As of now, all my REST api tests are api endpoint tests using trait('Test/ApiClient') and the testing experience + code confidence are incomparable to any other tests I write.

Ideally, I would like to also have a SocketClient trait so that I can register a fake socket Client to a channel, send some HTTP requests and then assert the messages received by my mocked socket Client.

Is there a better way of testing this and how would I go about mocking the Socket Client (which typically runs in the Browser) in node?

The app doesn't listen to IOS socket.

noticed the project is working fine with Android and Web not IOS.

I tried to solve the problem but nothing work.

I tried the IOS app with a node.js code and it's working fine but not with Adonis

I'm using Adonis version 3.2.1

This is my codes.

Ws.channel('/chat', 'ChatController').middleware('auth:jwt')

  • onTest (data) {
    console.log('test socket', data);
    }

IOS code: sample test app

var socket = SocketIOClient(socketURL: URL(string: "http://45.76.159.126:8080/chat?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXlsb2FkIjp7InVpZCI6MjYxfSwiaWF0IjoxNTM2NTgwNDQ3fQ.9eLKoX7eEd9OkHTpiyE0pOZPF-mRBr5MNQuF8mdWVW8")!, config: [.log(false), .forcePolling(true)])

override init() {
super.init()
socket.on("test") { dataArray, ack in
print("dataArray 1")
print(dataArray)
print("dataArray 2")
}

Access raw websocket data within middleware

Hi there, I'm new with Adonis and it's
websocket library & I need to access sent raw data(packet) & headers from the client in middlewares and channel controllers.
Is there any way to access all of that and modify some headers & add data to packet structure in response?!

Note: channel/topic name is not accessible via middlewares too. Is this a lack?! I need to do some stuff before grant access to channel's controller(without creating named specific middleware for each channel).

I've nothing found in the v4.1 documentation for now. Poorest documentation for such framework I've ever seen, don't hide us things 😁

Question about GraphQL Subscriptions and Adonis WebSocket

It's difficult to explain problem, but I will try:

I have tried to realize GraphQL Subscriptions (througs apollo subscriptions-transport-ws) with AdonisJS framework and WebSockets, and it works, but:

When I connect SubscriptionServer through adonis-websocket WS server - I works, but with some troubles, adonis-websocket send ping packets and after timeouts and limits it disconnect connections with clients. (it is correct logic, but GraphQL SubscriptionServer cannot work with it)

I had to connect GraphQL SubscriptionServer through new WebSocket server, it works fine, but ONLY if I disable Adonis WebSocket. Because two WS servers in one http server don't work correctly see issue

Therefore if I will use GraphQL Subscriptions, I cannot use Adonis WebSockets.. and same to backward...

I ask only your opinion, guys, and maybe some solution
Thank YOU!

PM2 support

Why this feature is required?

I want to run adonis production application using websockets with PM2 (http://pm2.keymetrics.io).
The problem is the inter-process broadcast messaging cannot be done just like this:

const cluster = require('cluster')
// this condition is false for every process run by pm2 because pm2 is the master daemon process
if (cluster.isMaster) {
  require('@adonisjs/websocket/clusterPubSub')()
  return
}

So after some research i found that i can use PM2 Programmatic API and included message bus to send messages between processes managed by pm2. See example (http://pm2.keymetrics.io/docs/usage/pm2-api/#send-message-to-process).

I wrote a simple PM2 module which uses pm2.launchBus and pm2.sendDataToProcessId methods to accomplish the same thing as require('@adonisjs/websocket/clusterPubSub')() does. The main part:

pm2.launchBus((err, bus) => {
  // listen for adonis ClusterHop event type
  bus.on('adonis:hop', ({ process: proc, data }) => {
    pm2.Client.getProcessByName(proc.name, (err, workers) => {
      workers.forEach((worker) => {
        if (worker.pm2_env.pm_id === proc.pm_id) {
          return
        }
        pm2.sendDataToProcessId(worker.pm2_env.pm_id, {
          type: 'adonis:hop', // event type is required to distinguish from other PM2 events
          topic: data.handle, // topic is required, just use handle
          data // event data for adonis ClusterHop - contains handle, topic and payload props
        }, (err, res) => {
          //
        })
      })
    })
  })
})

The problem is the difference between the format of messages that adonis messaging ClusterHop and PM2 bus implementation expects.

Messaging Adonis ClusterHop PM2 bus
process.send(packet) const packet = JSON.stringify({ handle, topic, payload }) const packet = { type: 'adonis:hop', data: { handle, topic, payload } }
process.on('message', (packet) => {} const message = JSON.parse(packet) const message = packet.data // if packet.type === 'adonis:hop'

Possible solutions

  • modify the current ClusterHop implementation to support both pm2 and pure adonis cluster i.e. use the PM2 bus one
  • add conditional PM2 implementation (check for process.env.pm_id) and fall back to current implementaion

Are you willing to work on it with little guidance?

Sure, i can send a PR for either first or second solution. Just tell me which one is better for you. Maybe out of the box support for pm2 module would be nice too. I can publish and maintain one by myself if you are not interested.

Thanks.

Combination Http and Ws

My problem: receive request (http or ws) from other servers.
For http: Don't know how to emit a message from http controller.
For ws: Don't know how other servers can connect to my server with normal socket (with adonis-websocket-client --> Stupid :v)
Anyone can help me?
Thank so much.

Issue broadcasting to dynamic channel

Basically, I'm implementing live notifications via the websocket connection. I'm just trying to get a working version of the flow going, I'm able to initiate everything properly, but i'm having problems broadcasting to that channel in a HTTP request.

socket.js

Ws.channel('notifications:*', ({ socket, auth }) => {
  if (auth.user.id !== socket.topic.split(':')[1]) {
    socket.emit('error', 'Invalid topic subscription. You may only subscribe to your own topic.');
    // socket.close()
  }

  socket.on('message', async (data) => {
    if (auth.user.id !== socket.topic.split(':')[1]) {
      socket.emit('error', 'Invalid topic subscription. You may only subscribe to your own topic.');
    }
    console.log(data)
    if (data.cmd === 'init') {
      socket.emit('init', await getNotifications()) 
    }
  })


}).middleware(['auth'])

routes.js

const Ws = use('Ws')

Route.get('sendws', async ({ request }) => {
  await Ws
    .getChannel('notifications:*')
    .topic('notifications:1')
    .broadcast('new:user')
});

I'm getting this error when calling the route:
Cannot read property 'broadcast' of null meaning the .topic isn't returning anything. I logged the Channel as below:

api_1              | Channel {
api_1              |   name: 'notifications:*',
api_1              |   _onConnect: [Function],
api_1              |   _channelControllerListeners: [],
api_1              |   subscriptions: Map { 'notifications:1' => Set { [Object] } },
api_1              |   _middleware: [ 'auth' ],
api_1              |   deleteSubscription: [Function: bound ] }

The subscription is there but the .topic() call is null. The documentation states this as an example so either the documentation is outdated/wrong or there is a bug in the code.

No compatible version found: uws@^0.13.0

Node v7.7.4 (npm v4.1.2)

When create a new adonis project from cli I am getting this error

xaamin$ npm install
npm ERR! Darwin 16.4.0
npm ERR! argv "/Users/nulldata/.nvm/versions/node/v7.7.4/bin/node" "/Users/nulldata/.nvm/versions/node/v7.7.4/bin/npm" "install"
npm ERR! node v7.7.4
npm ERR! npm v4.1.2
npm ERR! code ETARGET

npm ERR! notarget No compatible version found: uws@^0.13.0
npm ERR! notarget Valid install targets:
npm ERR! notarget 0.14.1
npm ERR! notarget
npm ERR! notarget This is most likely not a problem with npm itself.
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'adonis-websocket'
npm ERR! notarget

npm ERR! Please include the following file with any support request:
npm ERR! /Users/nulldata/Xaamin/NodeJS/headhunt-api/npm-debug.log

Some help is welcome. Thanks.

one mistake in websocket documentation

image

is the the following correct? in the above example ?
@adonisjs/websocket-client/clusterPubSub

isn't the following to replace above?

@adonisjs/websocket/clusterPubSub

I may be wrong too, please correct me

thank you .. you did awesome work

Channels list and usage?

#question

Hello,

Im building a chat application with Adonis, but I couldn't figure out how to:

  1. Dynamically create new chat rooms
  2. List all active rooms
  3. List all connected users within a room
  4. Presence

I would appreciate your assistance on this as I already chose adonis framework for my project and I wouldn't want to go back to socket.io again. :)

Thank you very much in advance.
Looking forward to hearing from you soon! @thetutlage

Access user model even if ws middleware doesnt have auth

So the issue I have is need access the this.auth.user is my websocket controller but for some reason the websocket channel requires the auth middleware attached to do so. It's a chat application so I need the users to receive chat messages but need to be logged in to send messages.

PS: im using jwt and lucid-mongo

Guys are crazy, why call the broadcast method if it works also like broadcastToAll in Channel/index.js, oh my God

Prerequisites

We do our best to reply to all the issues on time. If you will follow the given guidelines, the turn around time will be faster.

  • Lots of raised issues are directly not bugs but instead are design decisions taken by us.
  • Make use of our forum, or discord server, if you are not sure that you are reporting a bug.
  • Ensure the issue isn't already reported.
  • Ensure you are reporting the bug in the correct repo.

Delete the above section and the instructions in the sections below before submitting

Package version

Node.js and npm version

Sample Code (to reproduce the issue)

BONUS (a sample repo to reproduce the issue)

Count subscribe Client

It is possible that we can count client in a room

Ex.
We have Chat Room with Different Topic
And Many Clients subscribe Different Topic

When Client subscribe Any Topic then Count subscribed Client

it is possible

Websocket scalability

From @ed-fruty on September 20, 2018 17:57

From the docs I read this:

The websocket server scales naturally on Node.js cluster without any 3rd party dependencies like Redis. Also there is no need of sticky sessions.

It's pretty cool (I can suggest it handles by master process) but, it's only scalability on the one machine.

How it can be scale for several servers ?
If one connection will serve by one node, and the second connection in another node. So we can't send message from first node socket to another node sockets, isn't it?

Can we resolve this with adonis ?

I mean schema something like this

With socket.io it's just makes through redis adapter.

Copied from original issue: adonisjs/core#955

Cant emit/broadcast on dynamic topic

Im trying to emit on dynamic topic on certain channel but i cant make it work
this is the code that i use to test if i can get the channel object

i already tried this

const Ws = use('Ws')

class LocationController {
  constructor ({ socket, request, auth }) {
      this.socket = socket
      this.request = request
      this.auth = auth
  }

  async onNewLocation(data){
       const userId = 1234
        Ws.getChannel(`d:${userId}`).topic(`d:${userId}`).broadcast('sample')
  }
}

module.exports = LocationController

and this

const Ws = use('Ws')

class LocationController {
  constructor ({ socket, request, auth }) {
      this.socket = socket
      this.request = request
      this.auth = auth
  }

  async onNewLocation(data){
        const userId = 1234
        Ws.getChannel(`d`).topic(userId).broadcast('sample')
  }
}

module.exports = LocationController

and this is the code in client

import Ws from '@adonisjs/websocket-client'
export class AppComponent {
  title = 'app';


    constructor(){
        const ws = Ws('ws://localhost:3333', {
            path: 'websocket'
        })
        ws.connect()


        ws.on('open', () => {
            this.locationChannel(ws)
        })

    }

    locationChannel = (_ws) => {
        const userId = 1234
        const location = _ws.subscribe(`d:${userId}`)
        location.on('ready', () => {
            location.emit('newLocation', {latlng: '33.3632256, -117.0874871'})
        })

    }
}

and this is the error

TypeError: Cannot read property 'topic' of undefined
   at Channel.Ws.channel [as _onConnect] (/home/**/Code/adonis/**/start/socket.js:11:35)
    at process.nextTick (/home/**/Code/adonis/**-api/node_modules/@adonisjs/websocket/src/Channel/index.js:177:14)
    at process._tickCallback (internal/process/next_tick.js:61:11)

Strange behavior

Hey, if i need to send several WebSocket messages in a row from server to client - strange thing happens.

I have a SocketService that store all sockets.id when users subscribe to "user" room. For second message (status update) it's can't find socket.id at my SocketService class. It's looks like something had removed it, but SocketService.Delete() never happens (you can see that from log) and client don't disconnect from server.

I don't get why that happens. If i send status messages with some delay - all working as it should, but if there are few messages in 1 moment that thing happens. Any ideas what i am doing wrong?

Log

SocketService Add: 3
connected socket user#cjmwr1bya0000vww099sqtnfe 3

Event - WebSocket - updateAccountStatus slipross online
SocketService Get: { userId: 3,  socketList: { '3': 'user#cjmwr1bya0000vww099sqtnfe' } }
SocketService Found: 3

Event - WebSocket - updateAccountStatus slipross playing
SocketService Get: { userId: 3, socketList: {} }

WebSocket UserController

'use strict';

const SocketService = use('App/Services/SocketService');

class UserController {
	constructor({ socket, request, auth }) {
		this.socket = socket;
		this.request = request;
		this.auth = auth;

		SocketService.Add(auth.user.id, socket.id);
		console.log('connected socket', socket.id, auth.user.id);
	}

	onMessage(message) {
		console.log('receive message from socket', this.socket.id, message);
	}

	onClose() {
		console.log('disconnected socket', this.socket.id);
		SocketService.Delete(this.auth.user.id);
	}

	onError(error) {
		console.log('socket error', error);
	}
}

module.exports = UserController;

SocketService

let socketList = {};
class SocketService {
	Add(userId, socketId) {
		socketList[userId] = socketId;
		console.log('SocketService Add:', userId);
	}

	Delete(userId) {
		console.log('SocketService Delete:', userId);
		if (!socketList[userId]) return;
		delete socketList[userId];
		console.log('SocketService Deleted');
	}

	Get(userId) {
		console.log('SocketService Get:', { userId, socketList });
		if (!socketList[userId]) return -1;

		console.log('SocketService Found:', userId);
		return socketList[userId];
	}

	ToArray() {
		return Object.values(socketList);
	}
}

module.exports = new SocketService();

WebSocket event that send status updates to client. Here is all magic happens.

'use strict';

const Ws = use('Ws');
const SocketService = use('App/Services/SocketService');
const WebSocket = (exports = module.exports = {});

WebSocket.updateAccountStatus = async (dbAccount, status, data) => {
	const { account } = dbAccount;
	console.log('Event - WebSocket - updateAccountStatus', account, status);

	const user = await dbAccount.user().fetch();
	if (!user) return;

	const socketId = SocketService.Get(user.id);
	if (socketId === -1) return;

	const subscriptions = Ws.getChannel('user').topic('user');
	if (!subscriptions) return;

	data.account = account;
	data.status = status;

	await subscriptions.emitTo(
		'message',
		{
			type: 'status',
			data
		},
		[socketId]
	);
};

Is it suppose to work on version 4 also ?

I followed the instruction and got errors the first one
Error: Cannot find module 'adonis-fold'

And then
RuntimeException: E_INVALID_SERVICE_PROVIDER: WsProvider must extend base service provider class

JWT Auth in websockets

hi i am trying to implement jwt authentication in web sockets but i am not able to get auth object in web socket controller please guide me

Error

 {topic: "notifications", message: "Unexpected token       await auth.authenticator('jwt').check();"}

sockets.js

Ws.channel('notifications', 'NotificationController').middleware(['client_jwt_auth'])

NotificationController.js

  'use strict'
  const objUser = use('App/Models/User');

  class NotificationController {
    constructor({ socket, request, auth }) {
      this.socket = socket
      this.request = request
      // await auth.authenticator('jwt').check();
      // const User = await auth.getUser()
      try {
        await auth.authenticator('jwt').check();
        console.log('Auth to use jwt socket');
      } catch (error) {
        console.log(error)
      }
      // console.log('Orders Connected');
      console.log('user joined with ' + socket.id + ' socket id in group ' + socket.topic)
    }
    
  }

  module.exports = NotificationController

client side javascript code

let nws = null
nws = adonis.Ws().withJwtToken(JWToken).connect()
// nws = adonis.Ws().connect()

nws.on('open', () => {
    console.log('WS Connected')
    subscribeToChannel()
})

nws.on('error', (error) => {
    console.log('Error in WS : ' + error)
})

function subscribeToChannel() {
    const notifications = nws.subscribe('notifications')

    notifications.on('error', (error) => {
        console.log(error)
    })

    notifications.on('message', (message) => {
        console.log(message)
    })
}

An in-range update of sinon is breaking the build 🚨

Version 4.1.1 of sinon was just published.

Branch Build failing 🚨
Dependency sinon
Current Version 4.1.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

sinon is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ coverage/coveralls Coverage pending from Coveralls.io Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 5 commits.

  • 3a0e28b Update docs/changelog.md and set new release id in docs/_config.yml
  • 989e15b Add release documentation for v4.1.1
  • df3adf0 4.1.1
  • 0e9bf90 Update History.md and AUTHORS for new release
  • 9d9c372 Remove "engines" from package.json

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Inside event "close" cannot broadcast event.

I have recently update my code base from AdonisJS version 3.2 to the latest. With much effort, everything working right, but not new

@adonisjs/websocket

or

@adonisjs/websocket-client

package.
With old code base, a code like this should working:

Ws.channel("user", function(socket) {
    socket.on("disconnect", function() {
        socket.exceptMe().emit("closing", socket.id)
    })
}

As the code above, whenever socket connection disconnect (close browser, ...), other socket connection would be notified by event closing. But, with a new code base:

Ws.channel('user', ({ socket }) => {
    socket.on('close', () => {
        socket.broadcast("closing", socket.id)
    })
})

With event mapping from disconnect to close, and exceptMe().emit() to broadcast(), it doesn't work anymore. On the server, event close still be fire, but socket likely to not function anymore, so client could not receive closing event? I guess that this happened due to prevent not necessary emit when socket is going to be closed, I tried to find out, but I'm not good at tweaking source code to find out the problem.

My company project use AdonisJS, and my "boss" doesnt want to create a standalone socket server, so I must use builtin supported socket in AdonisJS. Please help me as soon as possible.
Thanks and best regard!

Websocket without adonis-websocket-client

Hi,

I'm trying to connect from a VueJS app (with MetinSeylan/Vue-Socket.io) to the web socket. But channels are not supported by socket.io on the client side. How can I response to events or use the presence feature in an AdonisJs app without a channel? Something like

Ws.channel('inquiries', 'InquiriesController').middleware('auth')

in socket.js does not work.

Regards,
Danny

Azure App Service

Error: Compilation of Β΅WebSockets has failed and there is no pre-compiled binary available for your system. Please install a supported C++11 compiler and reinstall the module 'uws'.
at e (D:\home\site\wwwroot\node_modules\uws\uws.js:31:19)
at Object. (D:\home\site\wwwroot\node_modules\uws\uws.js:35:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Ws.attach (D:\home\site\wwwroot\node_modules\adonis-websocket\src\Ws\index.js:99:23)
2017-01-28T13:12:39 Startup Request, url: /, method: GET, type: request, pid: 9140,4,19, ScmType: None

When an authenticated user, the websocket transmits this message: adonis: websocket connection is not in open state, current state 1 + 1ms

When an authenticated user, the websocket transmits this message: adonis: websocket connection is not in open state, current state 1 + 1ms

I am having this problem when I am logged into the application. I made the same code for when I'm logged out and works normally, following the step by step that exists in DOC.https: //adonisjs.com/docs/4.1/websocket

Can anyone explain what is missing or happening?

Package version

"version": "4.1.0",

Node.js and npm version

NODEJS = v12.16.2 NPM = 6.14.4

Code

start/socket.js


const Ws = use('Ws')

Ws.channel('chat', 'ChatController')
Ws.channel('channel', 'AdminChatController')

app/Controllers/Ws/AdminController.js


class AdminChatController {
  constructor ({ socket, request }) {
    this.socket = socket
    this.request = request
    this.message = {
      username: 'Admin Chat',
      body: 'Divirtam-se'
    }

    console.log(this.message);
    this.socket.emit('message', this.message)
  }

  onMessage (message) {
    this.socket.broadcastToAll('message', message)
  }
}

module.exports = AdminChatController

public/chat.js

const CHANNEL = 'channel';
let ws = null

$(function () {
  // Only connect when username is available
  // if (window.username) {
  //   startChat()
  // }
  startChat()
})

function startChat () {
  ws = adonis.Ws().connect()

  ws.on('open', () => {
    $('.connection-status').addClass('connected')
    subscribeToChannel()
  })

  ws.on('error', () => {
    $('.connection-status').removeClass('connected')
  })
}

function subscribeToChannel () {
  const chat = ws.subscribe(CHANNEL)

  chat.on('error', () => {
    $('.connection-status').removeClass('connected')
  })

  chat.on('message', (message) => {
    console.log(message)
    insertMessages(message)
  })
}

function insertMessages(message) {
  console.log(message);
  $('.chat-list').append(`
    <li>
      <div class="chat-image">
        <img alt="male" src="https://www.wrappixel.com/demos/admin-templates/pixeladmin/plugins/images/users/ritesh.jpg">
      </div>
      <div class="chat-body">
          <div class="chat-text">
              <h4>${message.username}</h4>
              <p> ${message.body} </p>
              <b>10.00 am</b>
          </div>
      </div>
    </li>
  `)
}

function sendNewMessage() {
  const message = $('#message').val()
    $('#message').val('')

    ws.getSubscription(CHANNEL).emit('message', {
      username: window.username,
      body: message
    })
}

$('#send-message').on('click', function() {
  sendNewMessage()
})

$('#message').keyup(function (e) {
  if (e.which === 13) {
    e.preventDefault()

    sendNewMessage()
    return
  }
})

An in-range update of mocha is breaking the build 🚨

Version 3.4.0 of mocha just got published.

Branch Build failing 🚨
Dependency mocha
Current Version 3.3.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As mocha is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • βœ… coverage/coveralls First build on greenkeeper/mocha-3.4.0 at 99.398% Details,- ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Release Notes v3.4.0

Mocha is now moving to a quicker release schedule: when non-breaking changes are merged, a release should happen that week.

This week's highlights:

  • allowUncaught added to commandline as --allow-uncaught (and bugfixed)
  • warning-related Node flags

πŸŽ‰ Enhancements

πŸ› Fixes

πŸ”© Other

Commits

The new version differs by 9 commits0.

  • 7554b31 Add Changelog for v3.4.0
  • 9f7f7ed Add --trace-warnings flag
  • 92561c8 Add --no-warnings flag
  • ceee976 lint test/integration/fixtures/simple-reporter.js
  • dcfc094 Revert "use semistandard directly"
  • 93392dd no special case for macOS running Karma locally
  • 4d1d91d --allow-uncaught cli option
  • fb1e083 fix allowUncaught in browser
  • 4ed3fc5 Add license report and scan status

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Broadcasting with Clustered Configuration

Package version

    "@adonisjs/ace": "^5.0.8",
    "@adonisjs/auth": "^3.0.7",
    "@adonisjs/bodyparser": "^2.0.5",
    "@adonisjs/cli": "^4.0.9",
    "@adonisjs/cors": "^1.0.7",
    "@adonisjs/fold": "^4.0.9",
    "@adonisjs/framework": "^5.0.9",
    "@adonisjs/ignitor": "^2.0.8",
    "@adonisjs/lucid": "^6.1.3",
    "@adonisjs/session": "^1.0.27",
    "@adonisjs/shield": "^1.0.8",
    "@adonisjs/vow": "^1.0.17",
    "@adonisjs/websocket": "^1.0.11",
    "@adonisjs/websocket-client": "^1.0.9",

Node.js and npm version

$npm -v
6.4.1
$ node -v
v11.1.0

Sample Code (to reproduce the issue)

server.js (straight out of the textbook)

const cluster = require('cluster')

if (cluster.isMaster) {
  for (let i=0; i < 4; i ++) {
    var worker = cluster.fork();
  }
  require('@adonisjs/websocket/clusterPubSub')()
  return
}

//console.log(cluster.worker.id)

const { Ignitor } = require('@adonisjs/ignitor')

new Ignitor(require('@adonisjs/fold'))
  .appRoot(__dirname)
  .wsServer()
  .fireHttpServer()
  .catch(console.error)

socket.js

Ws.channel('dispatch:*', 'DispatchController').middleware('auth')

DispatchController.js

class DispatchController {
  constructor ({ socket, request, auth }) {
    this.socket = socket
    this.request = request
    this.auth = auth
  }

  async onLocationUpdate(location){
    
    // Have tried like this
    this.socket.broadcast('updated:location',location);

    // And like this
    Ws
      .getChannel('dispatch:*')
      .topic('dispatch:3')
      .broadcast('updated:location',location);
  }

}

In the above example, I have n devices connected, and each device is broadcasting data once every 3 seconds. The information is then distributed to every other connected device. The trouble is once clustering is enabled, this ceases to work, and nobody get's each others messages.

Any ideas what I am doing wrong here, or if this is a bug?

Thanks!

How to close socket connection via middleware?

Dear,
I do the example follow: https://adonisjs.com/docs/4.1/websocket-server#_creating_middleware, and I modify some code like bellow

'use strict'

class CustomMiddleware {
  // for HTTP
  async handle (ctx, next) {
  }

  // for WebSocket
  async wsHandle (ctx, next) {
    ctx.socket.close() // I wan to close socket connection before it go to my ChatController
  }
}

module.exports = CustomMiddleware

But it not woking, socket never close. Is it bugs or what am I doing wrong?

I using adonisjs 4.1. my node version is 10.x

presence

I followed your tutorial on websockets and this line:

constructor ({ socket, request, presence }) {
    presence.track(socket,socket.currentUser.Id,{})
}

gets:

presence.track(socket,socket.currentUser.Id,{})
             ^

TypeError: Cannot read property 'track' of undefined

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.