Simple socket.io example not work - node.js

This is server file
var io = require('socket.io').listen(7000);
io.sockets.on('connection', function(socket) {
console.log("### new connection ###");
});
This is for client
$j(document).ready(function() {
var socket = io.connect('http://address.net:7000');
console.log(socket);
});
Server starts correct without any errors.
I copied from node_modules and attach to my site < head > section file "socket.io.min.js" file for client from dist folder.
And in output of server isn't any ### new connection ### when I run my site.
Why?

Problem resolved. It was about wrong server address in socket.io connection function.

Related

Node js with express return connection closed before receiving a handshake response

I have a socket running in nodejs and using this socket in html page this is working fine and some times I'm receiving the error on developer console as like
failed: Connection closed before receiving a handshake response. In this time my update not getting reflect on the user screen. Actually whenever the changes updated in admin screen I written the login in laravel to store this values into the redis and I have used the laravel event broadcast and in node js socket.io read the redis value change and push the values into the user screens.
I have code in laravel as like,
Laravel Controller,
public function updatecommoditygroup(Request $request)
{
$request_data = array();
parse_str($request, $request_data);
app('redis')->set("ssahaitrdcommoditydata", json_encode($request_data['commodity']));
event(new SSAHAITRDCommodityUpdates($request_data['commodity']));
}
In this above controller when the api call receives just store the values into this redis key and broadcast the event.
In my event class,
public $updatedata;
public function __construct($updatedata)
{
$this->updatedata = $updatedata;
}
public function broadcastOn()
{
return ['ssahaitrdupdatecommodity'];
}
Finally I have written my socket.io file as like below,
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis({ port: 6379 } );
redis.subscribe('ssahaitrdupdatecommodity', function(err, count) {
});
io.on('connection', function(socket) {
console.log('A client connected');
});
redis.on('pmessage', function(subscribed, channel, data) {
data = JSON.parse(data);
io.emit(channel + ':' + data.event, data.data);
});
redis.on('message', function(channel, message) {
message = JSON.parse(message);
io.emit(channel + ':' + message.event, message.data);
});
http.listen(3001, function(){
console.log('Listening on Port 3001');
});
When I have update the data from admin I'm passing to laravel controller, and controller will store the received data into redis database and pass to event broadcast.And event broadcast pass the values to socket server and socket server push the data whenever the redis key get change to client page.
In client page I have written the code as like below,
<script src="../assets/js/socket.io.js"></script>
var socket = io('http://ip:3001/');
socket.on("novnathupdatecommodity:App\\Events\\NOVNATHCommodityUpdates", function(data){
//received data processing in client
});
Everything working fine in most of the time and some times issue facing like
**VM35846 socket.io.js:7 WebSocket connection to 'ws://host:3001/socket.io/?EIO=3&transport=websocket&sid=p8EsriJGGCemaon3ASuh' failed: Connection closed before receiving a handshake response**
By this issue user page not getting update with new data. Could you please anyone help me to solve this issue and give the best solution for this issue.
I think this is because your socket connection timeout.
new io({
path:,
serveClient:,
orgins:,
pingTimeout:,
pingInterval:
});
The above is the socket configuration. If you are not configuring socket sometime it behaves strangely. I do not know the core reason, but i too have faced similar issues that implementing the socket configuration solved it.
Socket.io Server
Similar configuration should be done on the client side. There is an option of timeout in client side
Socket.io Client
For example.
Say this is your front-end code
You connect to the socket server using the following command:
io('http://ip:3001', { path: '/demo/socket' });
In your server side when creating the connection:
const io = require("socket.io");
const socket = new io({
path: "/demo/socket",
serveClient: false /*whether to serve the client files (true/false)*/,
orgins: "*" /*Supports cross orgine i.e) it helps to work in different browser*/,
pingTimeout: 6000 /*how many ms the connection needs to be opened before we receive a ping from client i.e) If the client/ front end doesnt send a ping to the server for x amount of ms the connection will be closed in the server end for that specific client*/,
pingInterval: 6000 /* how many ms before sending a new ping packet */
});
socket.listen(http);
Note:
To avoid complication start you http server first and then start you sockets.
There are other options available, but the above are the most common ones.
I am just describing what i see in the socket.io document available in github.socket_config. Hope this helps

socket io connection working fine in localhost but not when deploying on heroku server

When I am running my code on localhost it is working fine but after deploying on heroku it shows error (GET Error)
Here Is My Code
Server Side Code
app = express()
app.listen(app.get('port'), function() {
console.log('Node app is running on port..', app.get('port'));
});
var server = app.listen(4200);
var io = require('socket.io')(server);
io.on('connect',(socket)=>{
console.log('connected..........');
})
Client Side Code
private socket = io('My-Heroku-server-address:4200');
Error
https:My-Heroku-server-address:4200/socket.io/?EIO=3&transport=polling&t=MDpJszb
Instead of specifying the URL to connect in the client side code like private socket = io('My-Heroku-server-address:4200'); just do
var socket = io();
This will try to connect to the host that serves the page.
Refer Socket.IO for more information.
Thanks all.
Problem has been solved.
I just removed the port no.
private socket = io('My-Heroku-server-address');
Thanks all

Socket.IO, SSL Problems With cloudflare

I'm having a socket.io app that basically receives signals from a frontend in order to kill and start a new ffmpeg process (based on .spawn()).
Everything works like expected, but often I get a 525 error from cloudflare. The error message is: Cloudflare is unable to establish an SSL connection to the origin server.
It works like 9 out of 10 times.I noticed that more of these errors pop up whenever a kill + spawn is done. Could it be the case that something block the event loop and because of this blocks all incoming requests and cloudflare logs these as a handshake failed error?
Contacting cloudflare support gives me back this info (this is the request they do to my server):
Time id host message upstream
2017-08-16T09:14:24.000Z 38f34880faf04433 xxxxxx.com:2096 peer closed connection in SSL handshake while SSL handshaking to upstream https://xxx.xxx.xxx.xxx:2096/socket.io/?EIO=3&transport=polling&t=LtgKens
I'm debugging for some time now, but can't seem to find a solutions myself.
This is how I initialize my socketIO server.
/**
* Start the socket server
*/
var startSocketIO = function() {
var ssl_options = {
key: fs.readFileSync(sslConfig.keyFile, 'utf8'),
cert: fs.readFileSync(sslConfig.certificateFile, 'utf8')
};
self.app = require('https').createServer(ssl_options, express);
self.io = require('socket.io')(self.app);
self.io.set('transports', ['websocket', 'polling']);
self.app.listen(2096, function() {
console.log('Socket.IO Started on port 2096');
});
};
This is the listener code on the server side
this.io.on('connection', function (socket) {
console.log('new connection');
/**
* Connection to the room
*/
socket.on('changeVideo', function (data) {
//Send to start.js and start.js will kill the ffmpeg process and
start a new one
socket.emit('changeVideo');
});
});
Another thing that I observer while debugging (I only got this a few times):
The text new connection displayed on the server and the connected client emits the changevideo event but nothing happens on the server side instead the client just
keeps reconnecting.
This is a simplified version of the nodejs code. If you have more questions, just let me know.
Thanks!

Access SFTP from NodeJS

I have a need where i have to open a SFTP connection with a server, copy a file from there to local.
To that end, i have tried installing node-sftp module using
npm install node-sftp
It didnt work out of the box, i had to replace the sftp.js file that was installed by npm with that of github repository here : https://github.com/ajaxorg/node-sftp
(npm version was using TTY and github version was using PTY. i am not sure what they are)
After start the server and invoking the code, i see this in console.
launching: sftp -o Port=22 jash#xxx.63.xxx.49
listening...
console just hangs here. I am trying to print all files in the current directory after connection is opened.
This is the code
var http = require('http');
var Sftp = require('node-sftp');
var port = process.env.PORT || 1337;
var msgHandler = function(request, response) {
var options = {
host:"xxx.63.xxx.49",
username:"jash",
password:"mypassword",
port:22
};
var conn = new Sftp(options,function(err){
console.log(err);
});
conn.cd(".", function(err) {
console.log(err);
conn.ls(".", function(err, res) {
console.log(res[0].path);
});
});
console.log("listening...");
}
http.createServer(msgHandler).listen(port);
The credentials are fine, i used them in SecureCRT and was able to login.
The second argument to Sftp() (the function(err)...) is where you want to place your conn.cd(... code. It (said 2nd argument) is a function that gets called once the connection has been established. Make sure to check for err of course.

AppFog node.js client cannot load socket.io

I just deployed a node.js site to AppFog. It works fine locally when I go to "http://localhost:8080", but when I got to the one on AppFog: http://bandwithfriends.aws.af.cm/ I get the following Chrome console error:
XMLHttpRequest cannot load http://localhost:8080/socket.io/1/?t=1357769454152. Origin http://bandwithfriends.aws.af.cm is not allowed by Access-Control-Allow-Origin.
SERVER CODE:
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
static = require('node-static'); // for serving files
// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');
app.listen(process.env.VCAP_APP_PORT || 8080);
io.configure('development', function(){
io.set('transports', ['xhr-polling']);
});
CLIENT CODE index.html:
I am including socket.io like this:
<script src="/socket.io/socket.io.js"></script>
CLIENT CODE script.js:
var url = 'http://localhost:8080';
var socket = io.connect(url);
How do I fix this?
All I had to do to fix this was remove the url on the client side code:
var socket = io.connect();
Hope this helps anyone else having the same problem!
Both your client side and server side are wrong.
On the client side; make this change:
var url = io.connect('http://<your domain name>');
//For example: var url = io.connect('http://shash7.ap01.aws.af.cm');
On the server side, you need to implement socket.io like this:
var app = require('express')() , server =
require('http').createServer(app) , io =
require('socket.io').listen(server);
server.listen(80);
The above code was taken from the socket.io site. They changed the way socket.io listens in the 0.9 version so use the above version.
Other than that, everything looks fine. Tell me if you still can't figure this out.

Resources