Friday 9 June 2017

NodeJS and Websockets

Today is my first time using NodeJS, and Socket.io more particularly. I developed a website with a PHP framework and would like to add notification and chat features. I'm following the tutorial on the Socket.io website trying to adapt it to my needs, but I have a few questions.

  • First, I see that they are creating an HTTP server. What I want is the website to keep working as usual, meaning HTTP requests to be handled the same way, but on top of that I would like a websocket to be created whenever a page is loaded. So instead of

    var http = require('http').Server(app);
    http.listen(3000, function(){ console.log('listening on *:3000'); });
    
    

could we create a websocket server and use the WS protocol instead? I've seen a few libraries online but I would like to know if there is a standard one or a better way to do it.

  • The other thing is I can't find the right path to the server-side Socket.io script. Therefore the connection can't be established. From I saw online, it should look like DOMAIN/socket.io:3000. Now I'm getting lost since it's my first time using Node: where can I find this "socket.io" file on the server? In my project folder, all I see is a node_modules folder (which does include a socket.io folder but I'm not sure how to use it).

Please note that my script on the server runs without any errors, even though I haven't had a chance to establish a connection

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

http.listen(3000, function(){
    console.log('listening on *:3000');
});

io.on('connection', function(socket){
    console.log('a user connected');
});

Here's the current code on the client side:

var socket = io('<?php echo base_url(); ?>:3000, {path: "/sockets/socket.io"}');



via user1319182

No comments:

Post a Comment