Socket io heartbeat is not emitting - node.js

when i try to communicate with my socket io, the connection is established and the websocket writing is taking place, but the hearbeat is not getting emitted on the server ..so im not receiving anything on the client side. but when i disconnect and connect the server again, the old written message is getting emitted. please help me through this. thank you
I have tried with different port numbers, but its not working.
app.js (Server):
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(3000);
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log("Connected");
});
});
index.html (Client)
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

Socket.io might work unstable because of firewall or antivirus. This is actually a problem of WebSockets.
To solve this you may try to exclude WebSockets from the transports between client and server and specify on server side just XHR long polling and JSONP (as these two are the most stable):
io.set('transports', ['xhr-polling', 'jsonp-polling']);
I would also recommend to take a look at Engine.io. This framework is written by Socket.io author as the alternative, which works more stable.
The trick is following:
While Socket.io tries to connect via WebSockets first (when this attempt is fail, user will have to wait about 10 sec to switch to another transport), Engine.io tries to connect via XHR (which works in 100% cases), and meanwhile tries WebSocket connection, and if success - switching to WebSockets occurs.
Edit: Socket.io version 1.0+ is built on the top of Engine.io, so it has now all the benefits described above.

Related

Using net module in socket.io browser keeps loading

I want to use the tcp net module in node.js, my clients will be browser and also not browser ( device ).
when I tried to run in the browser the index.html, my browser keeps loading looks like it looping..I dont know what's wrong in my code.
I tried use telnet it works fine, the problem is on the browser i cannot load properly the index.html
//app.js
var net = require('net');
var io = require('socket.io')(net);
var clients = [];
var server = net.createServer(function (socket) {
console.log("New client connected");
clients.push(socket);
});
server.listen(1337, 'localhost', false, function () {
console.log('server bound');
});
io.on('connection',function(socket){
socket.emit('news', { hello: 'world' });
});
here is my client code.
http://pastie.org/10115599
Both the browser and socket.io require an http server, not just a TCP server. You can see the code examples in the socket.io documentation. The first server and client code example on that doc page shows you the basics you need.
In fact, the first step in socket.io connection is an http request that is then "upgraded" to the webSocket protocol. So, the server must be an http server. And socket.io hooks into an http server in order to receive incoming connections.
Here's a code example from the socket.io doc:
Server Code:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
app.listen(80);
io.on('connection', function (socket) {
// incoming socket.io connection established
});
function handler (req, res) {
// process http requests for normal web page serving
}
Client Code:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>

Node js - Socket.io-client is not connecting to socket.io server

I am trying to connect to a socket.io-client using the following code:
Server:
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res){
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Aw, snap! 404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
Client:
console.log('1');
// Connect to server
var io = require('socket.io-client')
var socket = io.connect('localhost:8080', {reconnect: true});
console.log('2');
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
console.log('3');
I don't get the Connected console log or Client Connected console log and I don't know why! The code sample is taken from another question posted: Link and I don't see any solution to the problem...
Use the same version of socket io client and server. It will work perfectly.
Also you need to add protocol with path.
change
var socket = io.connect('localhost:8080', {reconnect: true});
to
var socket = io.connect('http://localhost:8080', {reconnect: true});
Assuming you are using a socket.io version greater than 1.0, on the server, change this:
// Add a connect listener
io.sockets.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
to this:
// Add a connect listener
io.on('connection', function(socket) {
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
See the socket.io documentation reference here.
You don't want to be listening for this event only on already connected sockets. You want to listen for this event on any socket, even a newly created one.
Also, be very careful when reading socket.io code in random places on the internet. Some things changed significantly from v0.9 to v1.0 (I don't know if this was one of those things or not). You should generally always start with the socket.io documentation site first since that will always represent the latest version. Then, if looking at other internet references, make sure you only use articles that are later than mid-2014. If you don't know the vintage of an article, it's best not to rely on it without corroboration from a more recent article.
you can use localhost. It works for me as well. You must use your ip address and port that works for you

How do I connect two Socket.io servers/apps?

I'm trying to build an application that has two components. There's a public-facing component and an administrative component. Each component will be hosted on a different server, but the two will access the same database. I need to set up the administrative component to be able to send a message to the public-facing component to query the database and send the information to all the public clients.
What I can't figure out is how to set up a connection between the two components. I'm using the standard HTTP server setup provided by Socket.io.
In each server:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
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.on('my other event', function (data) {
console.log(data);
});
});
And on each client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I've looked at this question but couldn't really follow the answers provided, and I think the situation is somewhat different. I just need one of the servers to be able to send a message to the other server, and still send/receive messages to/from its own set of clients.
I'm brand new to Node (and thus, Socket), so some explanation would be incredibly helpful.
The easiest thing I could find to do is simply create a client connection between the servers using socket.io-client. In my situation, the admin server connects to the client server:
var client = require("socket.io-client");
var socket = client.connect("other_server_hostname");
Actions on the admin side can then send messages to the admin server, and the admin server can use this client connection to forward information to the client server.
On the client server, I created an on 'adminMessage' function and check for some other information to verify where the message came from like so:
io.sockets.on('connection', function (socket) {
socket.on('adminMessage', function (data) {
if(data.someIdentifyingData == "data") {
// DO STUFF
}
});
});
I had the same problem, but instead to use socket.io-client I decided to use a more simple approach (at least for me) using redis pub/sub, the result is pretty simple. My main problem with socket.io-client is that you'll need to know server hosts around you and connect to each one to send messages.
You can take a look at my solution here: https://github.com/alissonperez/scalable-socket-io-server
With this solution you can have how much process/servers you want (using auto-scaling solution), you just use redis as a way to forward your messages between your servers.

Socket.io - Cannot load file or io is not defined

I'm trying to set up a simple NodeJS - socket.io web application.
I have installed NodeJS and Socket.io on my Raspberry pi and I can start the server script without any problems.
I have downloaded the client socket.io, which I'm loading in the frontend script.
My problem is, whenever I try to connect to my server my browser gives me these errors.
Error: failed to require "socket.io" from "root"
...plete}}});require.register("learnboost-engine.io-client/lib/transports/websocket...
socket.io.js (linje 1)
ReferenceError: io is not defined
var socket = io.connect('http://192.168.0.105:8888');
Here is the server script.
var io = require('socket.io').listen(8888);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
console.log('Running fine');
Here is my frontend script.
<!--<script src="localhost:8080/socket.io/socket.io.js"></script>-->
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://192.168.0.105:8888');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
My Raspberry pi is hosting the nodejs - socket.io, and the website is hosted on my main computer with Wampserver.
I really hope someone can help me :) Thanks in advance.
Socket.io.js is hosted by NodeJS server, so you should connect to
<script src="192.168.0.105:8888/socket.io/socket.io.js"></script>
And
http://192.168.0.105:8888 is wrong, http means that you want to use port 80
.You should use 192.168.0.105:8888 instead.
it says here that
var socket = io()
connects to the host server by default, which means you don't have to put anything in there
http://socket.io/get-started/chat/

Unable to receive events in SOCKET.IO client

I am new to socket.io and i am trying out the examples mentioned on their site. I am going good with it but problem occurs when i try to use io.emit on the server side and try to receive on client side.
Here is my server code
var io=require("socket.io").listen(8888);
io.set('log level',1);
io.on('connection',function(socket){
socket.emit('hi');
console.log("Connected");
});
And my client's code
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket=io.connect("http://localhost:8888");
socket.set('log_level',1);
socket.on('hi',function(){
console.log('received');
});
</script>
The problem is i don't see the message 'received' in the console! The answer may be trivial but i tried experimenting but failed everytime. Please guide....
I am on ubuntu firefox. node version: 0.8.7
So you should have this on the serve side:
var io = require('socket.io').listen(88888);
io.set('log level',1);
io.sockets.on('connection', function (socket) {
socket.emit('hi);
console.log("Connected");
});
});
And you should have this on the client side:
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888/');
socket.set('log_level',1);
socket.on('hi', function () {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
WebSockets like many html5 features does not work in a non webserver environment. I mean It won't work if you are accessing your client with the file protocol.
You need to have a http server.
What I do to get things done easily, I use python built-in web-server. It does the job.
Just spawn it in you client folder like this:
python -m SimpleHTTPServer
And then point your browser to port 8000 (default).
I've made a boiler plate socket.io app that you can clone and even push directly to dotCloud.com
This is a simple example and could help you to get started with socket.io.
Look for examples on the soket.io GitHub page.
You wrote: io.on('connection' instead io.sockets.on('connection'
This code should work fine:
var io = require('socket.io').listen(8888);
io.set('log level', 1);
io.sockets.on('connection', function(socket){
socket.emit('hi');
console.log("Connected");
});

Resources