Skip to content

Instantly share code, notes, and snippets.

@cjpartridgeb
Last active August 29, 2015 14:12
Show Gist options
  • Save cjpartridgeb/6730e41d982c043d26d1 to your computer and use it in GitHub Desktop.
Save cjpartridgeb/6730e41d982c043d26d1 to your computer and use it in GitHub Desktop.
For l__q
var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var mysql = require( 'mysql' );
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
var clients = {};
var sockets = {};
// CONFIG
//////////////////////////////////////////////////
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
//////////////////////////////////////////////////
var save_message = function(message_from, message_content, callback) {
var message_time = parseInt((new Date().getTime())/1000, 10);
var post = { userid: message_from, message: message_content, data: message_time };
connection.query('INSERT INTO nodeshoutbox SET ?', post, callback);
};
//////////////////////////////////////////////////
//get user that matches the token
var get_user_by_token = function(token, callback) {
connection.query('SELECT * FROM users WHERE token = ? LIMIT 1', [token], callback);
};
//////////////////////////////////////////////////
io.set('authorization', function (handshakeData, cb) {
console.log('Auth: ', handshakeData.query);
cb(null, true);
//search user by id
get_user_by_token(handshakeData.query.token, function(err, result) {
if (0 == result.length) {
socket.emit('auth_login_response', 0);
return;
}
//if user found, add user details in clients object
clients[socket.id] = {
user_username: result[0].username,
user_id: result[0].id
};
sockets[result[0].id] = socket;
});
});
//////////////////////////////////////////////////
//////////////////////////////////////////////////
io.sockets.on( 'connection', function( client ) {
clients[socket.id] = {};
console.log( "New client !" );
//message sent event
client.on('message', function(message_from, message_content) {
//get user id of sender
message_from = clients[socket.id].user_id;
//save the message to db
save_message(message_from, message_content, function(err, message_id) {
//if there is a socket to send to
if (sockets[message_to]) {
//send the message
io.sockets.emit('message', { name: message_from, message: message_content, id: message_id });
}
});
});
});
server.listen( 1234 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment