2

I am trying to create a nodejs app that will search in various web sites using their API. The result will be sent to the client as soon as it receive result from those API using socket.io. The front end will then add those result using jQuery.

What is the best way to implement this?

So Far I have tried:

Sample code 1

At first I created a middleware for express that add the socket to the request like -

var socketMiddleWare = function(req, res, next){
  io.on('connection', function(socket){
    console.log(io.engine.clientsCount + " clients connected.");
    req.socket = socket;
    
    socket.on('disconnect', function(){
      console.log(io.engine.clientsCount + " clients after disconnec.");
    });
    
  });
  next();
};

then added this middleware to my route -

app.use('/users', socketMiddleWare, users);

It works but the problem is it create multiple event listener each time user refresh the page.

Sample code 2

So then I tried (sample code)

io.on('connection', function(socket){
  console.log("user connected");
  global.socket = socket;
  socket.on('disconnect', function(){
    console.log("disconnect");
  });
  
  socket.on('my message', function(){
    console.log("My message received");
  });
});

and on my test route I did

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  if(socket){
    socket.emit('response', 'nothing');
  }
  res.render('index', { title: 'Express' });
});

module.exports = router;

It solved the previous problem of multiple event listener on refresh But most of the time it can not emit the response. And even it emit my browser can not show the result. On client side I did something like this -

var socket = io.connect('http://localhost');

socket.on('response', function(data){
    console.log(data);        
    document.getElementById("change").innerHTML += data;
});

I can see the response in browser console but my browser show the change for a few milliseconds before it disappear.

I think the the main problem is The page loads before establishing socket connection.

I am currently learning node.js and socket.io. So please help me.

Conclusion

I do have plan to add social network features like one to one message, live friends feed update on home page etc using socket.io in future. Please let me know if there is any good documentation or open source project that can help me implementing it.

I am searching for solution for last couple of days but with no luck so far. I am ready to learn any new methodology or fully rewrite my code.

TL;DR

When a user client search for item, push contents to the client that requested the content when new data available. Data is available after processing response from website like "The Movie Database" and "TheTVDB.com" through their API.

1 Answer 1

1

You can use the ID of the socket to keep track of which socket to send results to.

Client

When the user then searches for something the ID is included in the query parameters.

<body>
    <form>
        <!-- Disable the search bar until the socket is connected -->
        <input type="search" name="q" placeholder="Search" disabled>
    </form>
    <div id="results"></div>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var resultsElement = document.querySelector("#results");
        var search = document.querySelector("form [type=search]");
        var socket = io("http://localhost:3000");


        socket.on("connect", function(){
            search.disabled = false;
        });

        socket.on("results", function(results){
            for(var i = 0;i < results.length;i++){
                var result = document.createElement("div");
                result.textContent = results[i];
                resultsElement.appendChild(result);
            }
        });

        document.querySelector("form").addEventListener("submit", function(event){
            fetch("/search?socketID=" + encodeURIComponent(socket.id) + "&q=" + encodeURIComponent(search.value));
            event.preventDefault();
        });
    </script>
</body>

Server

When the server receives the search request it gets the socket using the socket ID sent in the query parameters and starts sending results back to the client.

var app = require("http").createServer(handler);
var io = require("socket.io")(app);
var fs = require("fs");
var url = require("url");
app.listen(3000);

function handler(req, res) {
    var query = url.parse(req.url, true).query;
    if(req.url.startsWith("/search")){
        var results = ["things", "stuff", "items"];
        // Server-side IDs have "/#" in front of them
        var socket = io.sockets.connected["/#" + query.socketID];
        if(socket){
            // Get and send "search results"
            var interval = setInterval(function(){
                var popped = results.pop();
                if(popped){
                    socket.emit("results", [query.q + " " + popped]);
                }else{
                    clearInterval(interval);
                }
            }, 1000);
        }
        res.writeHead(204);
        res.end();
    }else{
        fs.readFile(__dirname + "/index.html", function(err, data) {
            res.writeHead(200);
            res.end(data);
        });
    }
}
3
  • Thanks for the response. My gobal.socket method is working good with my setup now. Because API response from external service needs time to process and meanwhile the socket connection get established. Apr 28, 2016 at 8:31
  • 1
    Have you tested searching from two places at once? Only one socket will get results.
    – metarmask
    Apr 28, 2016 at 10:18
  • I just tried to search two place at once in my global.socket code and all search result was pushing to only one client. Other clients got no response! Thanks @metarmask Apr 28, 2016 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.