Express.js and Socket.io - node.js

I'm building a chat system using Express and Socket.io.
I would like to understand which are the functionality of these two frameworks in this type of project, because consulting the APIs I got confused.
What are the differences bewteen this:
USING EXPRESS 3/4
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
and this:
USING WITH THE EXPRESS FRAMEWORK
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
I'm a lot confused, so I hope that somebody will explain this question.

If you are using Express 3 or 4 use the first one, if you're using an older version of Express, use the second one.

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>

Getting "socket hang up" using nodejs / socket.io and wscat

I have the following nodejs web socket server
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8000);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log("Listening on 8000");
When trying to connect using wscat
wscat -c ws://localhost:8000/
I get the following error
error: Error: socket hang up
It works just fine in browser with the following javascript
var socket = io.connect('http://localhost:8000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Help is appreciated!
I suggest that you try connecting to endpoint while specifying transport protocol. Like this:
wscat -c ws://localhost:3000/socket.io/\?transport=websocket
This works for my case.

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

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

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?

How to receive posts from Instagram API using Express.js on Node

I am trying to set up an app that will show Instagram posts in real time with a certain hashtag.
Here's what I have thus far.
var io = require('socket.io').listen(app)
, fs = require('fs')
, connect = require('connect')
, $ = require('jquery')
// , ngrok = require('ngrok')
, express = require('express')
, app = express()
, port = process.env.PORT || 5000;
//ngrok.connect(5000, function (err, url) {
//})
app.listen(port);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.emit('stuff', function() {
console.log("http server listening on %d", port);
});
socket.on('my other event', function (data) {
console.log(data);
});
});
// Defining Routes
app.use(express.static(process.cwd() + '/public'));
app.get('/', function (req, res) {
res.send('Testing');
});
app.get('/endpoint', function (req, res) {
// For convention's sake, we only respond to this if it's a properly formatted request from Instagram
if (req.query['hub.challenge']) {
// First we check if hub.challenge exists in the query, then we do something
res.send(req.query['hub.challenge']);
}
});
This is where I'm wrong/lost
app.use(express.bodyParser());
app.post('/endpoint', function (req, res) {
console.log(req.body);
});
I believe I've followed the Subscription tutorial in the Instagram API (set up hub.challenge and set up a subscription) but how do I see the incoming JSON data it's supposed to send? On top of that, how can I manipulate the JSON to show the pictures on the front end?
Any help is appreciated!

Resources