var socket; function connectToChatServer( server, port, userId, messageCallback) { socket = io.connect(server + "?userId=" + escape( userId), {port: port}); socket.on('connect', function () { //console.log("connected"); }); socket.on('im', messageCallback); socket.on('ping', function (msg) { socket.emit('ping', msg); }); socket.on('disconnect', function () { //console.log('disconnected'); }); socket.on('error', function ( reason) { //console.error("Unabled to connect to chat server", reason); }); socket.on('connect_failed', function ( reason) { //console.error("Unabled to connect to chat server", reason); }); } function sendChatMessage( userId, message) { if (socket) socket.emit('im', { userId:userId, message:message}); }