Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
mafintosh committed Apr 16, 2015
0 parents commit bb7d3c7
Show file tree
Hide file tree
Showing 9 changed files with 323 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Mathias Buus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
64 changes: 64 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# signalhub

Simple signalling server that can be used to coordinate handshaking with webrtc or other fun stuff.

```
npm install signalhub
```

Or to install the command line tool

```
npm install -g signalhub
```

## Usage

``` js
var signalhub = require('signalhub')
var hub = signalhub('http://yourhub.com')

hub.subscribe('/my-channel')
.on('data', function (message) {
console.log('new message received', message)
})

hub.broadcast('/my-channel', {hello: 'world'})
```

## API

#### `hub = signalhub(url)`

Create a new hub client

#### `stream = hub.subscribe(channel)`

Subscribe to a channel on the hub. Returns a readable stream of messages

#### `hub.broadcast(channel, message, [callback])`

Broadcast a new message to a channel on the hub

## CLI API

You can use the command line api to run a hub server

```
signalhub listen -p 8080 # starts a signalhub server on 8080
```

Or broadcast/subscribe to channels

```
signalhub broadcast my-channel '{"hello":"world"}' -p 8080 -h yourhub.com
signalhub subscribe my-channel -p 8080 -h yourhub.com
```

## Browserify

This also works in the browser using browserify :)

## License

MIT
47 changes: 47 additions & 0 deletions bin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#!/usr/bin/env node

var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
alias: {
port: 'p',
host: 'h'
},
default: {
port: 80
}
})

var cmd = argv._[0]

if (cmd === 'listen') {
var server = require('./server')()

server.on('subscribe', function (channel) {
console.log('subscribe: %s', channel)
})

server.on('broadcast', function (channel, message) {
console.log('broadcast: %s (%d)', channel, message.length)
})

server.listen(argv.port)
return
}

if (cmd === 'subscribe') {
if (argv.length < 2) return console.error('Usage: lobby subscribe [channel]')
var client = require('./')((argv.host || 'localhost') + ':' + argv.port)
client.subscribe(argv._[1]).on('data', function (data) {
console.log(data)
})
return
}

if (cmd === 'broadcast') {
if (argv.length < 3) return console.error('Usage: lobby broadcast [channel] [json-message]')
var client = require('./')((argv.host || 'localhost') + ':' + argv.port)
client.broadcast(argv._[1], JSON.parse(argv._[2]))
return
}

console.error('Usage: lobby listen|subscribe|broadcast')
12 changes: 12 additions & 0 deletions example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
var server = require('./server')
var client = require('./')

server().listen(9000, function () {
var c = client('localhost:9000')

c.subscribe('hello').on('data', console.log)

c.broadcast('hello', {hello: 'world'}, function () {
console.log('??')
})
})
29 changes: 29 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var ess = require('event-source-stream')
var nets = require('nets')

var noop = function () {}

module.exports = function (lobby) {
var that = {}

if (lobby.indexOf('://') === -1) lobby = 'http://' + lobby

that.subscribe = function (channel) {
return ess(lobby + '/v1/' + channel, {json: true})
}

that.broadcast = function (channel, message, cb) {
if (!cb) cb = noop
nets({
method: 'POST',
json: message,
url: lobby + '/v1/' + channel
}, function (err, res) {
if (err) return cb(err)
if (res.statusCode !== 200) return cb(new Error('Bad status: ' + res.statusCode))
cb()
})
}

return that
}
34 changes: 34 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"name": "signalhub",
"version": "0.0.0",
"description": "Simple signalling server that can be used to coordinate handshaking with webrtc or other fun stuff.",
"main": "index.js",
"dependencies": {
"corsify": "^2.1.0",
"end-of-stream": "^1.1.0",
"event-source-stream": "^1.2.0",
"minimist": "^1.1.1",
"nets": "^3.1.0",
"pump": "^1.0.0",
"size-limit-stream": "^1.0.0"
},
"devDependencies": {
"tape": "^4.0.0"
},
"scripts": {
"test": "tape test.js"
},
"bin": {
"signalhub": "./bin.js"
},
"repository": {
"type": "git",
"url": "https://github.com/mafintosh/signalhub.git"
},
"author": "Mathias Buus (@mafintosh)",
"license": "MIT",
"bugs": {
"url": "https://github.com/mafintosh/signalhub/issues"
},
"homepage": "https://github.com/mafintosh/signalhub"
}
80 changes: 80 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
var http = require('http')
var cors = require('corsify')
var collect = require('stream-collector')
var pump = require('pump')
var limiter = require('size-limit-stream')
var eos = require('end-of-stream')

var TTL = 30 * 1000

module.exports = function () {
var channels = {}

var get = function (channel) {
if (channels[channel]) return channels[channel]
channels[channel] = {name: channel, messages: [], subscribers: []}
return channels[channel]
}

var server = http.createServer(cors(function (req, res) {
if (req.url.slice(0, 4) !== '/v1/') {
res.statusCode = 404
res.end()
return
}

var channel = get(req.url.slice(4).split('?')[0])

if (req.method === 'POST') {
collect(pump(req, limiter(64 * 1024)), function (err, data) {
if (err) return

server.emit('publish', channel.name, data)
data = Buffer.concat(data).toString()

channel.messages.push([Date.now() + TTL, data])
for (var i = 0; i < channel.subscribers.length; i++) {
channel.subscribers[i].write('data: ' + data + '\n\n')
}
res.end()
})
return
}

if (req.method === 'GET') {
server.emit('subscribe', channel.name)
channel.subscribers.push(res)
for (var i = 0; i < channel.messages.length; i++) {
res.write('data: ' + channel.messages[i][1] + '\n\n')
}
eos(res, function () {
channel.subscribers.splice(channel.subscribers.indexOf(res), 1)
if (!channel.subscribers.length && !channel.messages.length) delete channels[channel.name]
})
return
}

res.statusCode = 404
res.end()
}))

var interval

server.on('listening', function () {
interval = setInterval(function () {
var names = Object.keys(channels)
var now = Date.now()
for (var i = 0; i < names.length; i++) {
var ch = channels[names[i]]
while (ch.messages.length && ch.messages[0][0] < now) ch.messages.shift()
if (!ch.subscribers.length && !ch.messages.length) delete channels[ch.name]
}
}, 10000)
})

server.on('close', function () {
if (interval) clearInterval(interval)
})

return server
}
35 changes: 35 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
var server = require('./server')()
var client = require('./')
var tape = require('tape')

server.listen(9000, function () {
tape('subscribe', function (t) {
var c = client('localhost:9000')

c.subscribe('hello').on('data', function (message) {
t.same(message, {hello: 'world'})
t.end()
this.destroy()
})

c.broadcast('hello', {hello: 'world'})
})

tape('broadcast and then subscribe', function (t) {
var c = client('localhost:9000')

c.broadcast('hello1', {hello: 'world'}, function () {
c.subscribe('hello1').on('data', function (message) {
t.same(message, {hello: 'world'})
t.end()
this.destroy()
})
})
})

tape('end', function (t) {
server.close()
t.ok(true)
t.end()
})
})

0 comments on commit bb7d3c7

Please sign in to comment.