Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use socket.io with ejs(embedded javascript) instead of html page in Node JS application?

On client side in browser as ejs page:

<script src="https://cdn.socket.io/socket.io-1.2.0.js">
</script>
<script>
var socket = io()
socket.on('message', function (msg) {
    console.log(msg)
})
</script>

On server side in Node Js:

var http = require('http').Server(app);
var io = require('socket.io')(http)
io.on('connection', function(socket){
    console.log('a user connected')
    socket.on('disconnect', function(){
        console.log('user disconnected')
    })
io.emit('message', json);
})

I'm not getting 'a user connected' log in Node Js console. Because var socket = io() is not working or what is the problem i don't know. Can i use socket.io in .ejs page? I need ejs and i also need socket.io in my application. Any help would be appreciated.

like image 306
JaySparkexel Avatar asked Feb 10 '17 09:02

JaySparkexel


Video Answer


1 Answers

Here is the solution that worked fine for me.

Server-side

var express     = require('express');
var app         = require('express')();
var server      = require('http').createServer(app);
var io          = require('socket.io')(server);
var ejs         = require('ejs');


app.set('view engine', 'ejs');
app.get('/', function(req, res) {
    res.render('index');
});

io.on('connection', function(socket) {
    console.log('a user connected');
    socket.on('chat message', function(msg){
        console.log('message: ' + msg);
      });
});

server.listen(process.env.PORT || 3000, function(){
    console.log('app running');
});

And here is the index.ejs code

client-side

        <form action="">
                <input id="m" autocomplete="off" /><button>Send</button>
        </form>
        <script src="/socket.io/socket.io.js"></script>
        <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
        <script>
           $(function () {
                var socket = io();
                $('form').submit(function(){
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
                });
            });
        </script>
like image 85
DeSpider Avatar answered Sep 30 '22 00:09

DeSpider