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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With