Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/cristovao-trevisan/socket.io-topic-router
Express like routing path middleware for socket.io
https://github.com/cristovao-trevisan/socket.io-topic-router
expressjs middleware routing socket-io
Last synced: 23 days ago
JSON representation
Express like routing path middleware for socket.io
- Host: GitHub
- URL: https://github.com/cristovao-trevisan/socket.io-topic-router
- Owner: cristovao-trevisan
- Created: 2017-05-11T19:50:37.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-07-24T21:00:01.000Z (over 7 years ago)
- Last Synced: 2024-03-23T09:45:02.060Z (9 months ago)
- Topics: expressjs, middleware, routing, socket-io
- Language: JavaScript
- Homepage:
- Size: 24.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# socket.io-topic-router
Express like routing middleware for socket.io
## Install
`npm install socket.io-topic-router`
## Usage
### Basic
#### Server
```javascript
const io = require('socket.io')(8080)
const ioRouter = require('socket.io-topic-router')()io.use(ioRouter)
ioRouter.route('foo/:bar', (params, [arg1, arg2], next, socket) => {
console.log(params, arg1, arg2)
// params.bar === '1234'
// arg1 === 'arg1'
// arg2 === 'arg2'
socket.emit('foo/1234', 'bar')
})
```#### Client
```javascript
const io = require('socket.io-client')var socket = io('http://localhost:8080')
socket.on('foo/1234', resp => {
console.log(resp)
// resp === 'bar'
})
socket.emit('foo/1234', 'arg1', 'arg2')
```### Multiple Callbacks
#### Server
```javascript
const io = require('socket.io')(8080)
const ioRouter = require('socket.io-topic-router')()const ensureAuth = (params, args, next) => {
var {username, password} = args[0]
if (username === 'admin' && password === '1234') {
next()
} else {
next(new Error('Need authentication'))
}
}io.use(ioRouter)
ioRouter.route('user/:id', ensureAuth, (params, args, next, socket) => {
var user = {name: 'Jack Sparrow'}
socket.emit('user/' + params.id, user)
})
```#### Client
```javascript
const io = require('socket.io-client')var socket1 = io('http://localhost:8080')
socket1.on('user/1', user => {
console.log('Socket 1:', user)
// user.name === 'Jack Sparrow'
})
socket1.emit('user/1', {
username: 'admin',
password: '1234'
})var socket2 = io('http://localhost:8080')
socket2.on('user/1', user => {
// never called'
})
socket2.on('error', err => {
console.log('Socket 2:', err)
// Need authentication
})
socket2.emit('user/1', {
username: 'admin',
password: 'not this'
})
```