Unable to get socket.io working on AWS server - node.js

I have a server hosted at Amazon Web Services. I am using socket.io with nodejs on my website. Following is the code:
Client Side-
function bindSocket(){
iosocket = io.connect('http://ec2-54-190-34-106.us-west-2.compute.amazonaws.com:8080');
iosocket.on('connect', function () {
alert('connected');
iosocket.on('message', function(message) {
//alert(message);
getNotificationData(message);
//document.getElementById("socket_div").innerHTML = message;
});
iosocket.on('disconnect', function() {
//alert('disconnected');
});
});
}
Server side-
var fs = require('fs')
, http = require('http')
, socketio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
//res.end(fs.readFileSync(__dirname + '/socket_test.html'));
res.end();
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
socketio.listen(server).on('connection', function (socket) {
console.log('new connection');
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
I get the following error message:
polling-xhr.js:261 GET http://ec2-54-190-34-106.us-west-2.compute.amazonaws.com:8080/socket.io/?EIO=3&transport=polling&t=LjIkBx8 net::ERR_CONNECTION_TIMED_OUT
I have been using the same code(with IPs changed) on digitalocean server. However, I migrated to AWS and I'm unable to get it working.
Any help would be highly appreciated.

I figured it out. The port itself had to enabled from the AWS security group. I added the rule and everything worked.
Hope this helps someone else.

You might not enable the socket ports in the AWS network security group. Also, you have to add the same ports in the ufw (firewall) list.
Open the inbound rules and add the custom port to the list.
Type the following command in the terminal to add the custom port in the ufw list.
sudo ufw allow 5005/tcp
NB: the port (5005 in the example) may vary according to your implementation.

Related

how to connect via WebSocket running on Ubuntu server

Im have hetzner server on which im trying to run WebSocket. Unfortunately I got stack so here is my code from test.js)
const https = require('https');
const fs = require('fs');
const ws = require('ws');
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
};
let server = http.createServer(options, (req, res) => {
console.log(req);
res.writeHead(200);
res.end();
});
server.addListener('upgrade', (req, res, head) => console.log('UPGRADE:', req.url));
server.on('error', (err) => console.error(err));
server.listen(8080, () => console.log('started on 8080'));
const wss = new ws.Server({ server, path: '/echo' });
wss.on('connection', (ws) => {
console.log('client connected');
ws.send('Hello');
ws.on('message', (data) => ws.send('Receive: ' + data));
});
wss.on('error', (e) => console.log(e));
* I got this code from some sources
After running the server I got message in console started on 8080. Nothing else... I tried to test it but I always got errors with no code. It looks like service where I tested it cannot find WebSocket. It is possible that problem actually in connecting to the serer.
Im not shure which path string should I use. I have hostname ubuntu-s**** and server IP 49.****. I did lots of attempts with 'wss://ubuntu-s***:8080/echo' and 'wss://49.***:8080/echo' but none of them gave any result
I still have no messages in console that cliend tried to connect :( Moreover I tried to run it on the local server (of course I removed SSL sertificates connecthion and changed server protocol to HTTP) and it works perfectly!!!
Thanks a lot for urs replies
UPD: message I got when trying to connect ws WebSocket connection to 'ws://49.***:8080/echo' failed:
First double check if the IP address is correct then change protocol to HTTP because you are using it on top of HTTP:
http://49.***:8080/echo

Can't get WebSocket Server running on a subdomain (Plesk, Linux, NodeJs, Express)

I’ve developed myself a little WebSocket Server which works perfectly (local - on my IDE). The problem is that I want to host it on my server managed with Plesk under a specific subdomain that I've created: ws.my-url.de.
This is my server.js file:
const {logInfo} = require('./logger');
const WebSocketServer = require('ws').Server;
const express = require('express');
const uuid = require('node-uuid');
const app = express();
const wss = new WebSocketServer({
server: app.listen(process.env.PORT || 8888)
});
logInfo('WebSocket Server successfully started');
wss.on('connection', ws => {
ws.id = uuid.v4();
logInfo(`Client connected: ${ws.id}`);
ws.on('message', function () {
logInfo(`New message from client: ${ws.id}`);
});
ws.on('close', function () {
logInfo(`Client: ${ws.id} closed connection`);
});
});
wss.on('close', function () {
logInfo('WebSocket Server stopped');
});
app.post('/', function (req, res) {
logInfo(req);
});
I've also implemented a logger that logs out to a file which works also great (directly on start e.g. my startup message) but inside the logs folder on my server is a yawning emptiness.
I really can't get my WebSocket Server running on my server. To leave no stone unturned, I've disabled the proxy mode from nginx but after trying to connect to wss://ws.my-url.de I'm getting this error:
WebSocket connection to 'wss://ws.my-url.de/' failed: Error during WebSocket handshake: Unexpected response code: 500
So I can say that my server is not starting. To be really sure (and to exclude other things), I've wrote a little http server found in the internet and this ran straight out of the box after pressing the Restart App button (I saw the response in the browser window):
const http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end('App is running…');
}).listen(process.env.PORT);
This is my configuration by the way:
When I open the URL after trying to start my WebSocket Server, I'm getting this error:
So what I'm doing wrong here? I don't want a page I can open, I just want to get this running as a little service which is accessible over my subdomain. I'm very overwhelmed with this and thankful for every person who can help me.

Can't get Hello World with Node.js in Cloud9

I can't figure out how to get my server to respond with Hello World.
I don't even know what IP address is. Is the ip listed on the tab of my terminal it?
I just created an EC2 environment with the default Node.js template.
Do I need to setup more things beforehand?
https://i.stack.imgur.com/4m85x.png
Try the solution bellow and let me know if you need any explanation:
const http = require("http");
const port = 3000; // make sure the port number is not used
const requestHandler = (req, res) => {
req.on('Error occurerd', (err) => {
console.error(err);
res.end();
});
res.end("Hello from AWS Cloud9!");
}
const server = http.createServer(requestHandler);
server.listen(port, () => {
console.log(`Server is listening on port ${port}!`);
// Run your script then copy past this url in your browser 127.0.0.1:3000
});

The nodejs net.createServer function results in a blank server.address value in Bluemix

The net module has a createServer function that allows you to create a network wrapper. This works fine on a local runtime of Nodejs, but when running in Bluemix it is unable to determine the host address. The server seems to get created, but upon further inspection I find the server.address to be blank.
var tls = require('tls');
var fs = require('fs');
var net = require('net');
var tunnelHost = (process.env.VCAP_APP_HOST || 'localhost');
var tunnelPort = 8888;
var server;
var gatewayOptions = {
host: 'http://cap-sg-prd-5.integration.ibmcloud.com/',
port: '15133',
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem'),
ca: fs.readFileSync('ca.pem')
};
console.log("starting createSecureTunnel");
//create a server end point to use as a network wrapper for the secure gateway
server = net.createServer(function (connListener){
console.log('net server created');
connListener.on('end', function() {
console.log('client disconnected');
});
connListener.on('uncaughtException', function(err){
console.log('exception caught: ' + JSON.stringify(err));
});
//connect to farside, local/private server
connectFarside(connListener, function(err, remoteSocket){
if (err){
console.log(err);
}
console.log('connection made');
remoteSocket.pipe(connListener);
console.log('remote socket connecte to local connListener');
connListener.pipe(remoteSocket);
console.log('local connListener connected to remote socket');
});
});
//setup listener for network wrapper
server.listen(tunnelPort, tunnelHost, function(){
console.log('tunnel created at: ' + tunnelHost +":"+ tunnelPort); //.address +":"+ server.address().port);
});
//createa a TLS connection to the secure gateway
function connectFarside(conn, callback) {
console.log("starting connectFarside");
try {
console.log("initiating farside connection");
var socket = tls.connect(gatewayOptions, function(){
console.log("tunnel connected to " + gatewayOptions.host +":"+ gatewayOptions.port);
callback(null, socket);
});
socket.on("error", function(err){
console.log("Socket error: " + JSON.stringify(err));
});
} catch(err) {
console.log(err);
callback(err);
}
}
Bluemix gives your app a port to run on, this is the reason it is not working in Bluemix. You are starting to start your app on port 8888 with the following line of code.
var tunnelPort = 8888;
It should be changed to
var tunnelPort = process.env.VCAP_APP_PORT || 8888;
The above line will read an environment variable called VCAP_PORT where Bluemix assigns a port to your app, if it is not running Bluemix it will run on port 8888.
Your app will be accessible over the web on port 80 and 443. Bluemix will load balance to your app for you.
You can specify the server address when listening to the server
var net = require('net')
var server = net.createServer(handler)
server.listen(port, address)
Try with address = '0.0.0.0' and see if it works
Partially solved by using the cf-autoconfig module. It helps to reconfigure modules for use on Cloud Foundry platforms. By including this as the first line in my app, it mostly works. It doesn't use the port number. But at least I can access the wrapper.
So I added this as the first line
require("cf-autoconfig");
Then I changed the server.listen to this
//setup listener for network wrapper
server.listen(tunnelPort, function(){
console.log('tunnel created at: ' + tunnelHost +":"+ tunnelPort); //.address +":"+ server.address().port);
});
Now if I use my app name, I can connect to the server created by net.createServer().
I would still like to know how to get the port to work, so this can be used inside of a web application to provide the tunneling.

ECONNREFUSED during socket connect in Node app on Openshift

ECONNREFUSED on socket connect in Node app on openshift servers, works on development machine.
Hi, I am trying to write simple app that needs to make a outgoing socket connection from my server.js ( that came with the pre-installed template). In my express routes i have something like
self.createRoutes = function() {
self.routes = { };
self.routes['/asciimo'] = function(req, res) {
var link = "http://i.imgur.com/kmbjB.png";
res.send("<html><body><img src='" + link + "' /></body></html>");
};
self.routes['/mycfg'] = function(req, res) {
var serviceSocket = new net.Socket();
serviceSocket.connect({port: 443, host:"www.google.com",localAddress:self.ipaddress}, function() {
console.log("connected!!");
});
serviceSocket.on("error", function (e) {
console.log("Could not connect to service " + e);
});
}
}
The self.address is t process.env.OPENSHIFT_NODEJS_IP which is 127.4.217.129 in my case.
I tried the code on my development machine it works fine. But fails with ECONNREFUSED on openshift servers. Any help would be appreciated. Thanks for your time.
The problem was Node version 0.6.25. I created a new app with node verison 0.10 and the same code works fine.
Try something like this instead
var host = process.env.OPENSHIFT_NODEJS_IP;
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({host: host, port: port});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
ws.send(message);
});
ws.send('something');
});
EDIT
My apologies I overlooked that you were making an external connection. After reproducing it locally I was able to connect by removing the localAddress on your Sockect.connect. After looking at the documentation and source a bit this makes sense. Making a connection to google and binding to a local ip won't work due to google not knowing this local ip.

Resources