Created
May 16, 2016 23:49
-
-
Save wegorich/5d1d86eb25c7cdcee6220e4be4958a82 to your computer and use it in GitHub Desktop.
4front minimal socket code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import api from './api'; | |
import io from 'socket.io-client'; | |
import {EventAggregator} from 'aurelia-event-aggregator'; | |
const MSG_DATA_CHANGE = "peer-msg"; | |
export class DataChannel { | |
static inject = [EventAggregator]; | |
constructor(ea:EventAggregator) { | |
var socket = io(SITE_URL); | |
this.p2p = socket; | |
this.ea = ea; | |
socket.on('connect', this.attached.bind(this)); | |
} | |
attached() { | |
this.p2p.on(MSG_DATA_CHANGE, this.channelMessage.bind(this)); | |
api.getMe().then(e=> this.connectUser(e)); | |
} | |
channelMessage(data, event = MSG_ADD_ITEM) { | |
console.log(JSON.stringify(data)); | |
this.ea.publish(data.event || event, data); | |
} | |
connectUser(user, event = MSG_ADD_USER) { | |
this.p2p.emit(event, { id: user._id, name: user.currentDevice.device_type}) | |
} | |
send(data, event = MSG_ADD_ITEM) { | |
data.event = event; | |
this.p2p.emit(MSG_DATA_CHANGE, data) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var io = require('socket.io'); | |
export function(server) { | |
io = io(server); | |
io.on('connection', function(socket) { | |
socket.on(MSG_DATA_CHANGE, function(data){ | |
if(data.to){ | |
// private message | |
io.to(data.to).emit(MSG_DATA_CHANGE, data) | |
} | |
else{ | |
// group message | |
boradcastTo(socket, data); | |
} | |
}); | |
socket.on(MSG_ADD_USER, function(data) { | |
socket.join(socket.group); | |
//send it self, but skip own ID | |
socket.emit(MSG_DATA_CHANGE, { event: MSG_GET_USER_LIST, list: rooms[socket.group].filter(e => e.id !== item.id)}); | |
//send to group | |
boradcastTo(socket, Object.assign({ event: MSG_ADD_USER }, item)); | |
}); | |
socket.on('disconnect', function() { | |
socket.leave(socket.group); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment