not able to obtain socket connection to node server hosted on heroku - javascript

I am trying to send data from one node server to another node server. But when i host the one server on heroku i am not able to obtain a socket connection.
Hope anybody can help. Thanks in advance
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var value = "default";
var PORT = process.env.PORT || 3000;
// var engines = require('consolidate');
// app.set('views', __dirname + '/views');
// app.engine('html', engines.mustache);
// app.set('view engine', 'html');
var app = express();
//var server = app.listen(PORT, () => console.log(`Listening on ${
PORT }`));
var server = require('http').createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('+Client connected successfully+');
socket.on('data', function (data) {
console.log('data from pi' + data);
});
socket.on('disconnect', () => console.log('Client
disconnected'));
});
//console.log(PORT + 'actual listening to'+server.address().port);
server.listen(PORT);
client.js
var io = require('socket.io-client');
var socket = io.connect('https://herokuappname.herokuapp.com/', {
reconnect: true });
console.log('2');
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});

Related

Socket io client cannot communicate to socket io server

Need your help/guidance/suggestion for our scenario.
Issue: I am having some trouble connecting socket io client to socket io server. The error I got after running this code is connection time out.
My server code is :
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ",port);
});
My client code is:
<script src = "socket.io.min.js"> </script>
<script>
var socket = io.connect(`wss://${document.location.hostname}:${port}`);
console.log(socket);
socket.on('done', (data) => {
console.log(data);
});
</script>
Your server code does not start in my node installation.
I correct your server code with this below and seems to work
fine on my node installation. You forgot to link express library
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const express = require('express');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.listen(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ", port);
});
You can do with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>

how to set max. of clients of socket io?

to my server are just two clients allowed to connect with. How to set the max of clients on two clients of socket.io?
this is how my server.js looks like:
var path = require('path');
var express = require('express'),
app = express(),
http = require('http'),
socketIo = require('socket.io');
var server = http.createServer(app);
var io = socketIo.listen(server);
server.listen(9000);
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + 'index.html'));
});
app.use(express.static(__dirname + '/'));
io.on('connection', function (socket) {
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
console.log("disconnect")
});
});
This is untested, but you should be able to check number of users on connection and change it on connect/disconnect.
Here is an example:
const connectedUsers = 0;
const maxUsers = 2;
io.on('connection', function (socket) {
if(connectedUsers + 1 > maxUsers){ // check if the new connection will exceed the max connections allowed
socket.disconnect(); // if so, disconnect the user and exit https://stackoverflow.com/a/5560187/11518920
return;
}
connectedUsers++; // otherwise + 1 to the connectedUsers
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
connecteUsers--; // on a disconnected decrease the connectedUsers count
console.log("disconnect")
});
});

socket.io not working with node server

I'm trying to set up my node server to update all the connected clients with new information in real-time. When I run the code below, the io.sockets.on('connection') callback is fired constantly, flooding the console with the message Client connected!, and the front-end is not being updated from socket.emit(). What am I doing wrong?
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var models = require('./models.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
// Connect to the Mongo database
mongoose.connect('mongodb://localhost/test');
bin/www.js
#!/usr/bin/nodejs
var debug = require('debug')('my-application');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function(data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
public/javascripts/update.js
var socket = io.connect('http://' + document.location.hostname + ':3000/');
socket.on('connect', function() {
console.log('Socket connected!');
socket.emit('message', 'Message from client');
});
socket.on('update', function(data) {
alert(data);
});
And when I end the npm process, the client begins to log
http://<ip>:3000/socket.io/?EIO=2&transport=polling&t=1498772846992-691 net::ERR_CONNECTION_REFUSED
I've read posts about the express router messing with the socket requests but I can't seem to get it working no matter what I try.
Can you try this setup?
EDITED:
app.js:
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function (req, res) {
res.render('index');
});
module.exports = app;
bin/www.js:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000', function () {
console.log('server listens on port 3000');
});
var io = require('socket.io')(http);
io.listen(server);
io.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function (data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
index.pug (or jade, they say jade is obsolete):
doctype html
html
body
h1 Testing socket.io
h3#status not connected
br
p#update update:&nbsp
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
socket.emit('message', 'Hello!');
});
socket.on('update', function (data) {
document.getElementById("update").innerHTML += data;
});
Calling app.listen (where app is the result of invoking express()) returns an HTTPServer, which can be used to setup the socket connection:
var server = app.listen(port);
var io = socket(server);
without manually running your solution, I'd guess that because you're creating a new HTTPServer to be feed into the socket, it's somehow getting hung in a loop.

How to make remote websocket connection to nodejs server on heroku

I'm trying to connect to a nodejs server over a websocket connection but can't get anything to work.
My server.js looks like this:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io', {
transports: ['websocket']
})(http);
var server_port = process.env.PORT || 8080
var server_ip_address = process.env.IP || '0.0.0.0'
app.listen(server_port, server_ip_address, function () {
console.log('listening on ' + server_ip_address + ":" + server_port);
});
My client.js (running on a raspberry pi also running nodejs) is:
var io = require('socket.io-client');
var socket = io.connect('http://<app-url>',
{
reconnect: true,
transports: ['websocket']
}
);
socket.on('connect', function(socket) {
console.log('Connected!');
});
I've also tried on openshift v2 (ports 8000 and 8443) and v3 and no luck there.
If anyone has done this recently please let me know how, thanks!
When debugging the client I get the message:
engine.io-client:socket socket close with reason: "transport error"
and on the server:
heroku[router]: at=error code=H13 desc="Connection closed without response"
It looks like a strange bug that happens sometimes, you should be able to get through by adding the path of your client library in the options like so :
var socket = io.connect('http://<app-url>:8080',
{
reconnect: true,
transports: ['websocket'],
path: "/lib/socket.io.js" //use the relevant path for your file
}
);
But you seem to be using the default options anyway, so you could just do :
var socket = io.connect();
Ok, it's working now. I modified the example in the heroku docs
I'm not quite sure why my server config doesn't work, but the following does work:
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var PORT = process.env.PORT || 3000;
var app = express();
var server = app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('Client connected');
socket.on('disconnect', () => console.log('Client disconnected'));
});
client.js (xShirase was right in saying I needed the correct path here...)
var io = require('socket.io-client');
var socket = io.connect('https://<url>',
{reconnect: true, transports : ['websocket'], path: '/socket.io'});
socket.on('connect', function (socket) {
console.log('Connected!');
});

express.Createserver() not working

I am beginner to nodejs. I tried below code. But server is not listening to the port and host.
var fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));
var host = config.host;
var port = config.port;
var express = require("express") ,http = require("http");
var app = express();
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
app.listen(port, host);
I also tried below code. But found in SO that this method is deprecated. And I replaced it with above code. Though it is not working. I also tried installing express globally then also not listening to port. What might be the problem.
var express = require("express");
var app = express.createServer();
app.get('/', function(request, response){
response.send("hello");
});
app.listen(port, host);
This is my config file.
[{
"host" : "127.0.0.1",
"port" : 1337
}]
config is array not object, you need to access it accordingly(or change the config) .Here is corrected code;
var fs = require("fs");
var config = JSON.parse(fs.readFileSync("config.json"));
var host = config[0].host;
var port = config[0].port;
var express = require("express") ,http = require("http");
var app = express();
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
var server = http.createServer(app);
app.get("/", function(request, response){
response.send("hello");
});
var server = app.listen(port, host);
server.on('error', function(err) {
console.log('error:' + err);
});
server.on('listening', function(){
console.log('server is up, all is well');
});

Categories