I'm integrating socket.io into my project. I'm using the code below and it's creating 6 connections after the first request. Is this normal?
server.listen(
port,
function()
{
console.log('Node.js server listening on port ' + port);
}
);
server.on(
'connection',
function(socket)
{
console.log('socket.io connection');
}
);
And here is the console.log output:
Node.js server listening on port 3000
socket.io connection
socket.io connection
socket.io connection
socket.io connection
socket.io connection
socket.io connection
You get this result because (as far as I understand) your server object is an instance of node's http.Server class, and is not connected with Socket.IO at all. In your example, 'connection' event is being fired on any request the your node server. It looks like browser sends 6 requests to your node server: page, favicon.ico, and 4 other requests (it might be images, javascripts, css, etc.).
To integrate socket.io into your project you may use the following code:
var http = require('http');
var sio = require('socket.io');
var server = http.createServer(function(req, res) {
//you request handler here
});
var io = sio(server);
io.on('connection', function(socket) {
console.log('socket connected');
//now you can emit and listen messages
});
var port = 3000;
server.listen(port, function() {
console.log('Node.js server listening on port ' + port);
});
And, of course, the official documentation might be very helpful. Good luck :)
Related
I am working on a web rtc project. I have create four files: index.html, server.js, client.js and package.json. My server is node.js. When I input node server.js, it produces nothing. Then, when i write on my web browser localhost:8080, it says upgrade required. Any solution? Please.
Thanks in advance.
This means that you have a http server listening on 8080 without websocket capabilities. Your webrtc client needs websocket to be able to talk with the server. You need also socket.io. Example:
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
This means that you have an http server listening on 8080 without WebSocket capabilities. Your webrtc client needs a WebSocket to be able to talk with the server. You need also socket.io. Example:
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(8080);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has dis
I've got a Vagrant box set up to port-forwards a socket.io application from internal port 5000 to external port 8081; when I try to connect from the client it starts long-polling the connection but I don't see any kind of response from the server and the server app never registers a connection attempt. The connection doesn't fail or return any error response code though, it just returns a 200 code with a blank response.
// Import utilities
var http = require('http'),
socketIO = require('socket.io'),
querystring = require('querystring');
// Init servers/external connections
var server = http.createServer(function baseHandler(req, res) {
// console.log(req.headers);
res.writeHead(200);
res.end(JSON.stringify({
message: 'This server only supports WebSocket connections'
}));
}),
io = socketIO(server);
server.listen(process.env.socket_port || 5000, function() {
var sockets = [];
console.log('App connected');
});
io.on('connection', function (socket) {
console.log('Socket connected');
console.log('Socket in rooms '+ socket.rooms.join(', '));
});
The same app works just fine when I'm trying to connect from the app running directly on my PC, so my code doesn't seem to be the problem here, especially given how it's basically duplicating the basic example in the docs; not really sure how to solve this from here.
This is one of those really stupid bugs which crop up when you're working on two different problems with the same codebase at the same time. Here's the client-side code line which was breaking:
var socket = io('127.0.0.1:8081/?access_token=1d845e53c4b4bd2e235a66fe9c042d75ae8e3c6ae', {path: '/auth/socket.io'});
Note the path key is set to point to a subdirectory, /auth, which is a leftover from my work to get an nginx folder proxying to an internal port which the server was working on.
I'm using express for my http server. I want to initialize the database connection first before I start to accept any http connection from client side. Some part of the code is as below.
function connect_to_db(connection_string) {...};
connect_to_db(connection_string);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
This doesn't work because the db connection takes time to be established. Before the connect_to_db is completed, the http server has already been started.
Any advice on how to make the code wait for the db connection to be established first?
you need to initialize server, when you can able to connect to database. You probably need some callback, when you are connected to database. e.g.
connect_to_db(connection_string, function(){
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
}
I am trying to connect my Node.JS (written using Sails.JS) app to another Node.JS server (Express4 / Socket.io) using socket.io-client.
My Sails Service app/services/Watcher.js looks like
var client = require('../../node_modules/sails/node_modules/socket.io/node_modules/socket.io-client');
// callback of the form function(socket)
exports.connect = function(callback) {
sails.log.debug("will connect socket to", sails.config.watcher.uri, "with Socket.io-client version", client.version);
var socket = client.connect(sails.config.watcher.uri);
socket.on('connect', function(){
sails.log.debug("connected");
socket.on('disconnect', function(){
sails.log.debug("Disconnected");
});
socket.on('error', function(err){
sails.log.debug("Could not connect", err);
});
callback(socket);
});
};
This is invoked from config/bootstrap.js as follows:
Watcher.connect(function(socket){
sails.log.debug("Connected watcher to relay with socket", socket);
});
On the Express side my server relay.js is as simple as:
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io').listen(http),
port = process.env.RELAY_PORT || 8000;
app.get('/', function(req, res) {
var response = {message: "some response"}; // to be implemented.
res.json(response);
});
http.listen(port, function () {
console.log("Relay listening on port " + port);
});
io.sockets.on('connection', function (socket) {
console.log("Connection opened", socket);
socket.on('disconnect', function () {
console.log("Socket disconnected");
});
});
When I run node relay it dutifully reports
Relay listening on port 8000
When I sails lift my other server it dutifully reports
will connect socket to http://localhost:8000 with Socket.io-client version 0.9.16
But I never see an actual connection.
If I point a browser at localhost:8000 I get the {"message":"some response"} JSON response I expect.
Why isn't my relay server accepting a connection from my socker.io-client app?
The issue here is probably that you're trying to re-use the
socket.io-client from inside of Sails. In general, if you're require()-ing dependencies of Sails directly in your project, you're heading in the wrong direction. In this case, socket.io-client caches configurations and connections, so your require isn't getting a fresh copy.
Instead, do
npm install socket.io-client#~0.9.16 --save
in your project and require with
var client = require('socket.io-client');
that'll give you a fresh copy of the socket client to work with, and avoid any conflicts with the Sails core's version.
I have a socket.io server in my app, listening on port 5759.
At some point in my code I need to shutdown the server SO IT IS NOT LISTENING ANYMORE.
How Can I accomplish this?
Socket.io is not listening on an http server.
You have a server :
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function(socket) {
socket.emit('socket_is_connected','You are connected!');
});
To stop recieving incoming connections
io.server.close();
NOTE: This will not close existing connections, which will wait for timeout before they are closed. To close them immediately , first make a list of connected sockets
var socketlist = [];
io.sockets.on('connection', function(socket) {
socketlist.push(socket);
socket.emit('socket_is_connected','You are connected!');
socket.on('close', function () {
console.log('socket closed');
socketlist.splice(socketlist.indexOf(socket), 1);
});
});
Then close all existing connections
socketlist.forEach(function(socket) {
socket.destroy();
});
Logic picked up from here : How do I shutdown a Node.js http(s) server immediately?
This api has changed again in socket.io v1.1.x
it is now:
io.close()
The API has changed. To stop receiving incoming connections you should run:
io.httpServer.close();