I am trying to follow tutorial on how to use socket.io with express.js framework and node.js.
Every tutorial I am following suggested I use the following lines to establish a connection in app.js
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
})
This worked if I use port other than 3000 which I am having to run my application on http://localhost:3000/. I get the error that Port 3000 already in use.
After debugging and looking at the code I think I have an idea of why is this happening. In ./bin/www.js file (created automatically by express js) we have the following lines:
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
but I am not sure how to reuse this created server with same port in my app.js. I am totally new to node.js. How do I setup socket io on the express framework the right way?
hello there please put your server.listen after socket connection like this
var app=require('expess')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
})
server.listen(3000);
I hope this would work.Thanks
In order to kill any existing node process, you can run killall node command in your shell.
Remove this line from your code, which is hardcoding the port number -
server.listen(3000);
and add something like this instead -
app.set('port', process.env.PORT || 3000);
app.listen(app.get('port'));
So your code would look something like -
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// server.listen(3000);
app.set('port', process.env.PORT || 3000);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
});
server.listen(app.get('port'));
Now when your run your app again, it would boot on port 3000 by default or you can pass an environment variable (PORT) while starting the server like this to run on other ports.
$ PORT=8080 node app.js
Related
I'm more or less following the socket.io documentation and trying to apply it to my slightly different project but I believe I'm making some mistake. I've used express-generator to create my project's skeleton and therefore I got app.js file, www file and route files.
I've put this code in www file:
var io = require('socket.io')(http);
console.log('Socket is running!');
io.on('connection', function(socket){
console.log('A User Has Connected: ' + socket.id);
});
This code in my footer file:
<script src="/socket.io/socket.io.js"></script>
<script src="/javascripts/jquery-3.2.1.min.js"></script>
<script src="/javascripts/javascript.js"></script>
</body>
</html>
And this in my JavaScript file:
$(document).ready(function(){
var socket = io();
});
Now I understand that when a request is made, the console should log "A User Has Connected: " + the id of the socket but I'm not getting anything other than "Socket is running!". I assume I'm missing something but can't figure it out and the documentation is using the same code.
var port = normalizePort(process.env.PORT || '8087');
app.set('port', port);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
You have to use the same server instance express-generator creates, which is the following line in www file
var server = http.createServer(app);
To use that, change
var io = require('socket.io')(http);
to
var io = require('socket.io')(server);
I'm very new for this stuff, and trying to make some express app
var express = require('express');
var app = express();
app.listen(3000, function(err) {
if(err){
console.log(err);
} else {
console.log("listen:3000");
}
});
//something useful
app.get('*', function(req, res) {
res.status(200).send('ok')
});
When I start the server with the command:
node server.js
everything goes fine.
I see on the console
listen:3000
and when I try
curl http://localhost:3000
I see 'ok'.
When I try
telnet localhost
I see
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
but when I try
netstat -na | grep :3000
I see
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN
The question is: why does it listen all interfaces instead of only localhost?
The OS is linux mint 17 without any whistles.
If you don't specify host while calling app.listen, server will run on all interfaces available i.e on 0.0.0.0
You can bind the IP address using the following code
app.listen(3000, '127.0.0.1');
If you want to run server in all interface use the following code
app.listen(3000, '0.0.0.0');
or
app.listen(3000)
From the documentation: app.listen(port, [hostname], [backlog], [callback])
Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
document: app.listen([port[, host[, backlog]]][, callback])
example:
const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
console.log("server is listening on 9000 port");
})
Note: 0.0.0.0 to be given as host in order to access from outside interface
I've read many posts on Nodejs and Expressjs for that matter but I still don't understand how this works:
This is the basic Hello World application with Express.js (taken from http://expressjs.com/starter/hello-world.html).
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
How are we able to get host and port using server when we are still in the process of getting what we'll eventually bind to the var server?
Because it's asynchronous. The callback is only being run later, after server is defined and initialized.
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Proper indenting sometimes helps see this.
I cannot get socket.io in node.js to work. When I start my server on port 3000 it never receives a connection even occurrence when I visit http://localhost:3000. I even tried copy and pasting the example code from the socket.io npmjs webpage.
Backend
var io = require('socket.io');
var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = io.listen(server);
app.use(express.static( __dirname + '/public'));
server.listen(3000);
io.sockets.on('connection', function (socket) {
console.log('connection established');
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log("Server started on port 3000");
index.html
var socket = io.connect('http://localhost:3000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
I am using socket.io v0.9.16 and express v3.4
I have extensively look on stack as well as the socket.io docs and can't figure out what is going on. This is killing me!
Note: There are plenty of "socket.io not working" questions on stack but I haven't found any that apply to my problem. The example I provided is almost literally the one from the socket.io npm reference.
Any working example, using the latest version of nodejs, will work; ideally, it's as simple as possible.
to use create a folder, npm install express socket.io then place in the three files, and 'node app.js'.
layout.jade
!!! 5
title=title
body!=body
index.jade
script(src='http://cdn.socket.io/stable/socket.io.js')
script
//create socket
var socket = new io.Socket();
//connect socket
socket.connect();
//on data recieved
socket.on('message', function(data){
//log data
console.log( data );
//modify data
data.modified = true;
//return data
socket.send(data);
});
app.js
// expressjs.com, a web framework
var express = require('express');
// socket.io, real time communications
var io = require('socket.io');
//create web server
var app = module.exports = express.createServer();
//configure web server
app.configure( function () {
app.set('views', __dirname);
app.set('view engine', 'jade');
app.use(app.router);
});
//handle requests for /
app.get('/', function (req, res, next) {
res.render('index', {
title: 'socket.io test'
});
});
// listen on port 8080
app.listen( 8080 );
console.log("Express server listening on port %d", app.address().port);
// attach socket.io to the web server
var socket = io.listen( app );
// when a client connects
socket.on('connection', function(client){
//send the client some data
client.send({ data: [1,2,3] });
// when the client sends back data
client.on('message', function (msg){
// log the data
console.log( msg );
});
});
Maybe, nowjs is that you want. It's provide simple API to call server functions from client.