Tuesday, 8 August 2017

Send Acknowledgment for socket.io event

Send Acknowledgment for socket.io event

Question: How to send Acknowledgment for socket.io event?
in node.js (Server side)
io.sockets.on('connection', function(socket){    

    /* Message Received from Client*/
    socket.on('chat_messsage', function(data, callback){        
        var responseData = { 'message':data.message, 'received':1};        
        callback(responseData); //Send Acknowledgment to the client
    });


});

Client Side JavaScript
var socket = io.connect('http://localhost:3000');
socket.on('connected', function (data) {    
    
    //Send message to Server with callback function
    socket.emit('chat_messsage', {message:"this is message"}, function(response){
        console.log(response); //console the Acknowledgment
    });

});



Question: How to Send additional data on socket connection?
Client side, connect with parameter
  var socket =  io.connect(chatURL,{ query: "req_from=browser" });


Sever side, Detect the client Connection.
io.on('connection', function (socket) {
  console.log(socket.handshake.query['req_from']);
});


Question: How to connect node with http and https?
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey  = fs.readFileSync('cert/server.key', 'utf8');
var certificate = fs.readFileSync('cert/server.crt', 'utf8');

var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);

//http connect
httpServer.listen(8080);
//https connect
httpsServer.listen(8443);