Can't seem to get socket io to display any emits - node.js

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

Related

Socket.io emit not working (by visiting URL)

I am developing an app that gets a signal from external hardware equipment. I catch this signal by redirecting it to a certain URL in my app: '/impulse/:id'.
I am able to catch the signal, but the emit function inside the app.get('/impulse/:id') is not triggering. The console logs are...
How can I make the emit function work?
Below is my server.js script, where I catch all the socket signals and prevent the external call from being redirected to the index page.
...
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
const socket = require('socket.io');
app.use(express.static(__dirname + '/public'));
app.use('/api', appRoutes);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://HERE IS MY DB INFO...', function(err) {
if (err) {
console.log('Not connected to the database: ' + err); // Log to console if unable to connect to database
} else {
console.log('Successfully connected to MongoDB'); // Log to console if able to connect to database
}
});
var server = app.listen(port, function() {
console.log('Running the server on port ' + port); // Listen on configured port
});
var io = socket(server);
io.on('connection', function(socket){
socket.on('join', function(data){
var gameroom = data.gameid;
console.log("joined: " + gameroom)
socket.join(gameroom);
})
//FUNCTION I WANT TO TRIGGER
socket.on('impulse', function(data){
console.log('IMPULSE')
io.emit('impulseReceived', {
})
})
})
//PLACE WHERE I EMIT
app.get('/impulse/:id', function(req, res){
console.log('Impulse Received')
var time = req.query.TIME;
var gameroom = req.params.id;
io.on('connect', function (socket) {
socket.emit('impulse', {
})
})
res.json({ success: true, message: 'received the time!'})
})
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/app/views/index.html')); // Set index.html as layout
});
Replace this whole
io.on('connect', function (socket) {
socket.emit('impulse', {
})
}
with this
io.emit('impulse', {})

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.

socket.io client not receiving message

When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!

how to attach socket.io to SwaggerExpress

I am using swaggerexpress middleware and swagger.
I can't get to work with socket.io
What is the proper way to attach socket.io to my server created?
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
var io = require('./api/helpers/socketio');
module.exports = app;
var config = {
appRoot: __dirname
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
swaggerExpress.register(app);
app.listen(10010, function () {
console.log('Application is start listening on localhost:10010');
});
io.on('connection',function(socket){
console.log("A user is connected: " + socket.id);
io.emit('message', "Welcome")
});
});
io.attach(app);
With that approach, my server is not getting up, got an error on socket.io attaching to app.
If you're okay using a different port for socket.io, you could do something like this:
var io = require('socket.io')(10011);
// Or maybe in your case:
// var io = require('./api/helpers/socketio')(10011);
io.on('connection', function(socket) {
console.log('user connected');
});
On the client you'd connect to it like this:
var socket = io('http://localhost:10011');
socket.on('connect', function() {
console.log('Socket connection established');
});

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

Resources