Not able to get Socket Message to ejs - node.js

I'm trying to pass the message from Node JS to Front end using socket. But, the message does not get transmitted.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const path = require('path');
const PORT = process.env.PORT || 5000;
io.on('connection', function(socket){
io.emit('order', "Order Updated");
console.log("Order Updated");
});
app.use(express.static(path.join(__dirname, 'public')))
.set('views', path.join(__dirname, 'views'))
.set('view engine', 'ejs')
.get('/', (req, res) => res.render('pages/index'));
http.listen(PORT, function(){
console.log('listening on *:' + PORT);
});
The console log is getting printed as Order Updated. In the index.ejs file I have the following code and I do not see any console log in the UI.
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
socket.on('order', function(msg){
console.log(msg);
window.scrollTo(0, document.body.scrollHeight);
});
});
</script>
Update 1
Based on the following answers, I updated the code to :
io.on('connection', function(socket) {
socket.emit('order', "Order Updated");
});
Update 2
$(function () {
var socket = io.connect('http://127.0.0.1:5000', {transports ['polling']});
socket.on('order', function(msg) {
console.log(msg);
});
});
Image of Server side console log :

Maybe on your server side, you have to emit to your connected socket like this ?
io.on('connection', function(socket){
socket.emit('order', "Order Updated");
console.log("Order Updated");
});
EDIT
On my client side, I'm connecting with host:port like this, and it works properly
var socket = io.connect('http://127.0.0.1:5000', {transports: ['polling']});
socket.on('order', function(msg) {
console.log(msg);
}
EDIT 2
On my index.html (client side), I'm also calling socket.io like this :
<script src="/socket.io/socket.io.js"></script> <!-- directly get from Node.js server -->
Hope it helps.

You should emit only to the connected socket:
io.on('connection', function(socket) {
socket.emit('order', 'Order Updated');
});
Otherwise you are emitting to all of the connected clients, which is probably not what you want.
EDIT:
You have to specify the port on which you are connecting in your socket.io instatiation code:
var socket = io('http://localhost:5000');
It's also adviseable to store the URL and the port in variables, so that you can configure them easily when deploying to production environments.

Related

what could be the error in socketio when using with express?

I have tried many methods to connect socket-io client and server with express but its not working and now i do not know what could be error.
i have tried to clone example available on socket-io website still it does not show any connectivity or any functions do not emmit.
This is server.js and this is my code i have made many changes in it but not working.
var express = require('express');
var app = express();
var path = require('path');
//require socket.io
var http = require('http').createServer(app);
var io = require('socket.io')(http);
//Setup a public path to load files
app.use(express.static('public'))
//app.use(express.static(path.join(__dirname, 'public')));
//Route for index
app.get(('/'),(req,res)=>{
res.send('index');
});
//Socket connection
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
app.listen(3000,()=>{
console.log('server running on port 3000');}
);
This is index.html that the server.js is sending i only included the script
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I expect it to console log when socket is connected and disconnected and emit the functions normally.
Hello Here is your working example of socket.io
In Your server code
const express = require('express')
const app = express();
//Listen on port 3000
server = app.listen(3000, () => {
console.log('server running on port 3000');
})
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', (socket) => {
console.log('New user connected')
socket.emit('news', { hello: 'world' });
})
Here is HTML code
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

connecting refused for web socket socket.io

I am loading my scripts using
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="/js/chat.js"></script>
My chat.js script is :
var socket = io();
socket.on('connect', function(){
var chatForm = document.forms.chatForm;
if (chatForm) {
var chatUsername = document.querySelector('#chat-username');
var chatMessage = document.querySelector('#chat-message');
chatForm.addEventListener("submit", function(e){
console.log("working")
//prevents page from reloading
e.preventDefault();
//emit the message with the socket
socket.emit('postMessage',{
username: chatUsername.value,
message: chatMessage.value,
});
chatMessage.value='';
chatMessage.focus();
});//chatform event
socket.on('updateMessages', function(data) {
showMessage(data);
});//update messages
}//chatForm
})
function showMessage(data) {
var chatDisplay = document.querySelector('.chat-display')
var newMessage = document.createElement('p');
newMessage.className = 'bg-success chat-text';
newMessage.innerHTML = '<strong>' + data.username + '<strong>:</strong>' +
data.message
chatDisplay.insertBefore(newMessage, chatDisplay.firstChild);
}
My app.js file uses:
app.set('port', process.env.PORT || 3000 );
var server = app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
io.attach(server);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
I am getting the following errors in my console and have no idea how to fix them. Somebody please help!
The server is listening on port 3000. My console is saying that there is an unhandled 'error' event
In your app.js file, you should connect socketIO before listening:
const socketIO = require('socket-io');
const io = socketIO(app);
io.on('connection', function(socket) {
console.log("user connected");
socket.on('postMessage', function(data) {
io.emit('updateMessages', data);
});
});
app.set('port', process.env.PORT || 3000 );
app.listen(app.get('port'), function() {
console.log('Listening on port ' + app.get('port'));
});
Let try it, because I think after listening, everything won't work. We should connect socketIO before listening.

In openshift Nodejs Socket.io responce 200 Ok, But console.log value not visible. my socket is working?

created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});

Can't seem to get socket io to display any emits

I've been trying to figure out why I can't get any emits to show up in my terminal and it seems that everything is running fine.... except for seeing the emits. Here is my code
var express = require('express');
var path = require('path');
// Create a new Express application
var app = express();
var views = path.join(process.cwd(), 'views');
app.use("/static", express.static("public"));
// Create an http server with Node's HTTP module.
// Pass it the Express application, and listen on port 3000.
var server = require('http').createServer(app).listen(3000, function() {
console.log('listening on port ' + 3000)
});
// Instantiate Socket.IO hand have it listen on the Express/HTTP server
var io = require('socket.io')(server);
var game = require('./game');
app.get('/', function(req,res) {
res.sendFile(path.join(views, 'index.html'));
});
io.on('connect', function(socket) {
io.emit('connection', { message: "You are connected!" });
game.initGame(io, socket);
socket.emit('connected', { message: "You are connected!" });
io.sockets.emit('test', 'test')
});
Any help would be great!
Emits are not automatically printed. socket.emit will send a message back to the client, not to the terminal. Use console.log("whatever") to print to the terminal:
io.on('connect', function(socket) {
console.log('Client connected');
socket.on('test', function(data) {
console.log("Got message of type 'test'containing data:", data);
});
});

Node.js socket.io server callback not working

I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>

Resources