Socket.io + Express | io.on('connection' ...) not fired - node.js

I've a little Express-Server and want to fire up some socket.io connection
Here is, what I have on Server-Side:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.all('*', function(req, res, next) {
res.header("Content-Type", "text/plain");
res.header("Access-Control-Allow-Origin", "*");
next();
});
app.get('/run', function(req, res, next){
io.on('connection', function (socket) {
socket.on('client_data', function (data) {
console.log('Message: '+data.message);
});
});
});
server.listen(8002, function() {
console.log('Listening on port %d', server.address().port);
});
Here is what I have on client side:
<script src="http://host:8002/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://host:8002");
socket.emit('client_data', {'message': 'hello there!'});
</script>
Now, when i go to my browser and type in http://localhost:8002/run it will jump into my "app.get('/run'..)"-Part in my app.js on server ...but unfortunately it will NOT execute io.on('connection'..){}-part and for this reason I will not get the output in my console send from the client. Some Ideas or solution on this issue?
Edit: Ok, it must have something to do with the fact, that my io.on('connection') is running withing the app.get('/run')-Part. Because if i put my io.on('connection')-Part in the server.listen()-Part...it works. Someone any idea why it dosnt work inside?

Related

Not able to get Socket Message to ejs

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.

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);
});

I'm unable to connect to socket

I'm trying to connect to a socket.But I did not get the socketid on the console.Is it the right way of connecting to a socket ?Can anyone please suggest me ...
My code :
var app = express();
var dir = process.cwd();
app.use(express.static(dir)); //app public directory
app.use(express.static(__dirname)); //module directory
var server =require('http').createServer(app);
var io = require('socket.io')(server);
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
client code :
var socket = io('http://localhost:8085/socket_issue');
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log(data);
});
socket.on('disconnect', function(){});
You seem to not have a server.listen() in your backend code.
I've edited the server code and it functions correctly:
var app = require('express')();
var dir = process.cwd();
var server =require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.of('/socket_issue').on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
Don't forget to change the port on the front-end and it'll work as expected:
Socket connected :Y7zi7dLRxqBA5nakAAAA

Make two socket connections talk to each other

Here is the scenario...
I am working on an app I had an idea for, I'm building it in ember with an express backend. I am using the express-ws so I can run the ws websocket package inside express better. I was not able to get just ws to work with express.
My app will have two people connecting to two different url's that are socket connections, so that they can send and receive information to the server without the other getting it. At least that's the way I've come up in my mind to do it.
What I want is when one user does an interaction over the socket, for that socket to send a message to the other socket to perform an action and send it's information to the user connected on it.
I hope that makes sense. With express-ws here is what I have done so far which works at a basic level.
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
app.use(function (req, res, next) {
console.log('middleware');
req.testing = 'testing';
return next();
});
app.get('/', function(req, res, next){
console.log('browser connected');
res.send('welcome to the api browser');
});
app.ws('/', function(ws, req) {
console.log('socket connected');
var object = {
message: 'welcome to the socket api',
time: Date.now().toString()
}
ws.send(JSON.stringify(object));
});
app.listen(1337);
I haven't made the other connection yet but for the time being it will be the same, but when the user on one connection sends a certain message to their socket, I want that socket to perform something and then pass some data to the other socket so it can send some information to it's user.
This might give you an idea of how to store the references for later use:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
// array to hold the connections
var openChannels = [];
app.use(function(req, res, next) {
console.log('middleware');
req.testing = 'testing';
return next();
});
app.get('/', function(req, res, next) {
console.log('browser connected');
res.send('welcome to the api browser');
});
app.ws('/', function(ws, req) {
console.log('socket connected');
// store connection for later reference
openChannels.push(ws);
// #todo: remove from array on disconnect
// set broadcast callback
ws.onmessage = function(msg) {
openChannels.forEach(function(index, item) {
if (item !== ws) { // make sure we're not sending to ourselves
item.send(msg);
}
});
};
var object = {
message: 'welcome to the socket api',
time: Date.now().toString()
}
ws.send(JSON.stringify(object));
});
app.listen(1337);

Routing with restify and socket.io in node

I have a node app which routes the request based on the url using restfy.
Now in want to bring socket into picture. But app doesnot redirect to the function when when socket.io is used. I am using FlexSocket.IO library in flex.
Here's my code snippet.
// In app.js
var restify = require('restify')
, http = require('http')
,socket = require('./routes/socket');
var app = restify.createServer();
app.get('/', socket.handle);
app.post('/', socket.handle);
var io = require('socket.io').listen(app);
app.listen(8080, function() {
console.log('%s listening at %s', app.name, app.url);
});
io.configure(function() {
io.set('transports', ['websocket','flashsocket']);
io.set('flash policy port', 843);
});
exports.io = io;
//In socket.js
exports.handle = function (req, res, next) {
console.log('In Handle'); //doesn't print this
io.sockets.on('connection', function(client){
console.log('Connection establiished');
});
In Flex
private var socket:FlashSocket;
socket = new FlashSocket("localhost:8080");
socket.addEventListener(FlashSocketEvent.CONNECT, onConnect);
socket.addEventListener(FlashSocketEvent.MESSAGE, onMessage);
protected function onConnect(event:FlashSocketEvent):void
{
Alert.show('connect'); //This alert is shown.
}
Is there anything wrong with the code? Why is the socket.handle function not called in node?
In app.js, try
var io = require('socket.io').listen(app.server); //app.server instead of just app

Resources