Socket IO net::ERR_CONNECTION_REFUSED - node.js

I am trying to implement socket.io into my application which is hosted at Azurewebsites. webapp
Here is the server.js
var app = require('express')();
var server = require('http').createServer(app);
server.listen(process.env.PORT || 3001)
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log("Socket connected :"+socket.id);
socket.emit('news', { hello: 'world' });
});
And Here is the client side socket. index.html
<script src="socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:3001');
console.log("scoekt connect",socket)
socket.on('connect', function(){ console.log('connected to socket'); });
socket.on('error', function(e){ console.log('error' + e); });
socket.on( 'news', function( data ){
console.log("socket data",data);
});</script>
I am getting the below error
I am not really sure whats is going wrong. Here is the structure of file-ing system
ROOT
app/
index.html
server.js
web.config
PS: this is an Angular2 application
PS: I have checked all the suggested question based on this error but none solved my issue, thus i am posting this question.

Per my experience, Azure Web App doesn't bind loaclhost or 127.0.0.1 to your website, and only ports 80 and 443 are public-facing. This maps to a specific port for your app to listen to, retrievable via process.env.PORT. So you'd need to replace
var socket = io('http://localhost:3001');
with
var socket = io('http://<your app name>.azurewebsites.net');
And if your server side and client side in the different domain, you'd also need to enable CORS on the server side. In Azure, we can enable it with the Azure portal.
In a browser, go to the Azure portal, and navigate to your App Service.
Click CORS in the API menu.
Enter each URL in the empty Allowed Origins text box. A new text box is created. As an alternative, you can enter an asterisk (*) to specify that all origin domains are accepted.
Click Save.
Socket.IO uses WebSockets, which are not enabled by default on Azure. You can also enable WebSocket support using the Azure Portal. Please see the steps below.
In the Azure portal, click Application settings in the SETTINGS menu.
Under Web Sockets click On
Click Save.
For more info, please refer to this documentation.

Related

Express-Socket.IO App isn't working with my Azure WebApp

For educational purposes I try to deploy an Express Server that is using Socket.IO. The Server should be able to deliver a static HTML Site that was built with React, answer with a "Hello Azure!" message whenever I make a GET Rest Call to http://localhost:4000/api/azure and whenever a new client connects to the site, all the other clients get a message announcing the new client.
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const router = require('./api/azure');
const PORT = process.env.PORT || 4000;
io.on('connection', () => {
console.log('A new user has connected!')
io.emit('broadcast', 'A new user has connected');
});
app.use(express.json());
app.use('/api/azure', router);
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.static('public'));
app.use('/', (_, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(PORT, () => {
console.log(`Listening to http://localhost:${PORT}`);
});
All this tasks are fulfilled without problems in localhost. The problem begins after this app is uploaded to one of my Azure WebApps.
Instead of delivering the message "Hello Azure!" when I call the https://mydomain.azurewebsites.net/api/azure it responses back with the HTML file.
The typical Socket.IO GET method for polling
https://mydomain.azurewebsites.net/socket.io/?EIO=4&transport=polling&t=SomeString
responses back with the HTML file, too.
Everything url extension that I give, gives me back the HTML file.
I barely know the basic stuff about WebApps. Maybe there is a configuration that I am forgetting? By the way I haven't done anything in the configuration except that I enabled the Websockets in the WebApp config.
This never happened before. The only difference is that right now I am using a free-tier just to test. Could it be that? If not, what am I doing wrong?
Thank you for your time!
To begin with, try turning the Web Socket config off as it applies to an IIS setting which tends to contradict with the Node.js websocket implementation.
If this doesn't help, try and force the transport layer to use Websockets and SSL.
io.configure(function() {
// Force websocket
io.set('transports', ['websocket']);
// Force SSL
io.set('match origin protocol', true);
});
Also, you cannot use arbitrary ports (port 4000 in your case) on services like App Service. Your app will be provided a port via process.env.PORT. So ensure that you are refering to the correct port from your log message. You should be able to see these in your log stream.
Also note, that Azure has launched a fully managed service called Web PubSub to power your apps with Web Sockets. The app service web socket implementation does not scale horizontally, this where Web PubSub will help you.
https://azure.microsoft.com/en-in/blog/easily-build-realtime-apps-with-websockets-and-azure-web-pubsub-now-in-preview/

How to test maximum connection Node JS websocket

I'm writing an Node JS socket App.
Case1: Base on this link
stackabuse.com/node-js-websocket-examples-with-socket-io/
I start the server on port 3000, go to browser, navigate to localhost:3000, i got index.html page and an connection to socket inside this file (you can find it in the link above).
This is my code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
console.log(current);
});
io.on('connection', function(socket){
//console.log('a user connected');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Case 2: I include socket.io.js file inside index.html file, then access it from browser (but not with port 3000 anymore) with apache like an normal site).
Code for Node server case 2
Then the script will create an websocket to localhost:3000 like this:
Client case 2
I only can test the maximum connect with case 1 (actually send alot GET request to get "index.html" page, not an real socket connection). I tested with thor, loadtest, benchmark, Artillery... and they're only work with case 1 :(
So, can I have any tool to test maximum connection in Websocket Node JS? I really need an usable tool to test websocket (not just HTTP GET).
Thansk for reading this question, and sorry for my English, by the way :(

Socket.io + Azure web sockets issue

I am working on a multiplayer chess game with NodeJS and socket.IO.
I have problem hosting it on Azure tho.. I tried many different approaches, a few mentioned:
Forcing the application to only use WebSockets by adding the code below:
io.configure(function() {
io.set('transports', ['websocket']);
});
Added <webSocket enabled="false"/> in web.config file..
Note: This disables the IIS WebSockets module, which includes its own implementation of WebSockets and conflicts with Node.js specific WebSocket modules such as Socket.IO. If this line is not present, or is set to true, this may be the reason that the WebSocket transport is not working for your application.
Matching origin protocol to ensure no SSL issues.
io.configure(function() {
io.set('match origin protocol', true);
});
I now started from scratch, since I thought my server-side part was corrupt, and tried Socket.io chat example instead.
I followed the steps.
Created a new web app on Azure.
Published my files through FileZilla FTP.
Enabled Web Sockets on Azure for my app (disabled by default).
STILL THE SAME ERROR! See picture below.
Anyone? I am unsure if it's a client-side or server-side issue. It seems like it's trying to XHR-poll instead of using web sockets..
Thanks in advance.
I got it working, thank you Chris Anderson-MSFT for your help.
The weird thing that occurred for me when deploying with FTP was that my node_modules folder differed with version(s) specified in my package.json.
I solved this by connecting my web app on Azure to a local Git repository and deploying the app through git. This connects my packages recursively and matches correct versions.
I also needed to enforce my client-side socket-io to use web sockets by specifying transport method:
var socket = io({transports:['websocket']});
And this is what my server-side file ended up looking like:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/default.html');
});
io.on('connection', function(socket) {
io.set('transports', ['websocket']);
console.log('new connection on socket.io');
socket.on('move', function(msg) {
socket.broadcast.emit('move', msg);
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});

Azure free website NodeJS websocket no longer connecting

I have an Android app that uses websockets via a NodeJS server hosted with Azure. For the passed six months, everything has been fine. Today, all is not fine. When I try to connect to my server, I get the response "No address associated with hostname."
I have websockets enabled in my config tab in the management console, also in the web.config file so that Node handles the websocket and not iis. I have changed nothing, toggled the websocket settings, nothing works. I have restarted the server many times. I also created a new website and migrated everything, still the same issue. I cannot get tech support from Microsoft because the website is a free one. I am aware that there is a max of 5 connections to the websocket; this is not the issue.
My server is using the 'ws' websocket module. I have taken my server.js code down to the minimum for testing. This is it now...
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: process.env.PORT || 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {});
ws.on('close', function closing(code, message) {});
if (ws.readyState == 1)
ws.send('message from the server!');
});
It still does not work. I replaced the entire file with the code below and the server responds with text in the browser. Of course, this is not websocket, but it shows that the server is able to respond to http requests.
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Hello, world!');
}).listen(process.env.PORT || 8080);
Has anything changed with the usage of websockets? Have recent restrictions been placed I am unaware of?

Socket.IO on Heroku does NOT work without SSL

I have a chat server setup as such:
var port = Number(process.env.PORT || 5000);
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app, {'log level':1, 'match origin protocol':true})
, fs = require('fs')
io.set('authorization', function (handshakeData, callback) {
console.log(handshakeData);
callback(null, true);
});
and then I handle some events:
io.sockets.on('connection', function(socket) {
socket.emit('handshaken', {id:socket.id}); // for HTML clients
socket.on('subscribe', function(roomId) {
doSubscribe(socket, roomId);
});
socket.on('unsubscribe', function(roomId) {
doUnsubscribe(socket, roomId);
});
socket.on('chat', function(data) {
doChat(data);
});
});
The client is on a different domain.
When I use the chat server via https, then everything is working fine. All the events are received. However, when I use http, I can see that the client can receive the 'handshaken' event, but nothing else is sent or received.
I wonder if this has anything to do with the socket.io authorization not working properly with non ssl connection.
However, in local environment, I can still use non ssl http://localhost:5000 as the chat server url without any issue. Is it also possible that this is an issue with Heroku?
UPDATE 1: After some investigation, if I use http url for the chat server, the server can emit to the client. The client can connect to the server, but cannot emit anything to the server (the server does not receive any emit).
Update 2: Some further investigations revealed that the chat server, under http, does received an emit, but only 1 emit. Any emit after that is not received.
It turned out that Sophos antivirus for Mac is the culprit here. After I disabled all web protection, my chat app works fine.
The interesting point here is that Sophos only targets Chrome browser, as Firefox and Safari work without any problem.

Resources