node.js Websocket raspberry pi 4B ERR_CONNECTION_REFUSED - node.js

During this last days I'been trying to run a node.js web through raspberry pi 4 connected to a private network as a server running in ubuntu server. At first time it worked in my laptop with Windows 10.
The steps are:
Install:
yarn install
Run ReactJS Client:
yarn start
Run NodeJS Server (in a separate terminal window):
node server.js
And the code in the file server.js is:
const http = require('https');
const socketIO = require('socket.io');
const DeepSpeech = require('deepspeech');
const VAD = require('node-vad');
let DEEPSPEECH_MODEL = __dirname + '/deepspeech-0.6.0-models'; // path to deepspeech english model directory
let SILENCE_THRESHOLD = 200; // how many milliseconds of inactivity before processing the audio
const SERVER_PORT = 4000; // websocket server port
// const VAD_MODE = VAD.Mode.NORMAL;
// const VAD_MODE = VAD.Mode.LOW_BITRATE;
// const VAD_MODE = VAD.Mode.AGGRESSIVE;
const VAD_MODE = VAD.Mode.VERY_AGGRESSIVE;
const vad = new VAD(VAD_MODE);
etc.
And I get this error:
polling-xhr.js:267
GET http://localhost:4000/socket.io/?EIO=3&transport=polling&t=N3VNHWo
net::ERR_CONNECTION_REFUSED
Any idea?

Related

micropython client from raspberry pi pico cannot connect to local host

I have a node.js server in which I am trying to send data in real time from my raspberry pi pico w over sockets.
My Simple Server is setup as follows:
const express = require("express")
const app = express();
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors")
const server = http.createServer(app)
const io = new Server(server, {
cors: {
origin: "*",
}
})
io.on("connection", (socket) => {
console.log('User Connected: ${socket.id}');
})
app.get('/', function(req, res, next) {
res.send("Hello world");
});
server.listen(80, () => {
console.log("Server is running")
})
The code I am running on the client side on my Raspberry Pi Pico W is as follows:
import time
import socket
import network
ssid = '<name>'
password = '<password>'
# Just making our internet connection
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print(wlan.ifconfig())
c = socket.socket()
c.connect(('http://127.0.0.1/',80))
print('Connected')
After ensuring the server is working just fine (i setup a react client and was able to transfer information), I am still unsure why my micropython-based client on my microcontroller cannot setup a socket. I keep getting the error:
Traceback (most recent call last):
File "<stdin>", line 32, in <module>
OSError: [Errno 103] ECONNABORTED
If someone could guide me on potential solutions that would be extremely helpful. Thanks!
The python socket library is for the lower level TCP connection to 127.0.0.1 on port 80.
HTTP and WebSockets are a layer on top the raw socket and require a specific client or socket code that understands each protocol.
Socket.io is another layer on top of those providing a way to negotiate a connection via HTTP or WS and the subsequent message formatting.
Plain sockets
A simple node socket server looks like:
const net = require('node:net')
const server = net.createServer(function(socket) {
socket.write('Echo server\r\n')
socket.pipe(socket)
})
server.listen(1111, '127.0.0.1')
Which you connect with:
c.connect(('127.0.0.1',1111))
HTTP
HTTP is likely the easiest route. I think urequests is bundled most of the time, or writing the HTTP request to the raw socket is not overly hard to implement yourself.
Using HTTP will have some overhead compared to sockets/web sockets, if you are streaming large amounts of data.
WebSockets
On the python side you would need a client like micropython-uasyncio-websockets (not sure if this is useful, just searched). This would require a server like the ws library provides on the node server side.
Socket.io
It might be hard to find an up to date socket.io library that works with micropython.

Node-osc sometimes sends OSC too often: related to IP address?

I have a local Node.js app on port localhost:3000. I'm using node-osc to message to MaxMSP. My code checks every 2 seconds if there is a reason to send the message (this is related to machine learning and webcam). 95 % of the time this works fine; OSC message might be sent now, then after 2 minutes, then after 10 seconds etc.
However, sometimes the OSC messaging goes crazy by sending a message every two seconds, despite my webcam and machine learning classifications staying the same. If there are no triggering changes, no messages should be sent. I have been thinking if this could be related to the fact that I sometimes change the location and respective IP address where my app functions. Could the system become unstable when switching between two IP addresses? I don't (yet at least) have proof that the "overheating" would come straight after changing the IP address.
Combining OSC with Node.js is new to me so I'm happy for any insights regarding the problem.
Some snippets:
server.js
const express = require("express");
var cors = require('cors');
const app = express();
let broadcaster;
const port = process.env.PORT || 3000;
const http = require("http");
const server = http.createServer(app);
const io = require("socket.io")(server);
const { Client, Message } = require('node-osc');
const client = new Client('xxx.xxx.x.x', 5000); // this IP I keep changing
socket.on("param", function(data) {
console.log(data);
let address = data.address;
client.send(address, data.val);
});
broadcast.js
if (newLabel== "a human" && newLabel !==oldLabel){ // checks this + other changes every 2 seconds
socket.emit("human");
sendParam ("/sound", 4);
}
function sendParam(adr, val) {
let data = {
address: adr,
val: val
};
socket.emit('param', data)
}

parse-Server cloudCode with nodejs

I am using parse-server and I want to use nodejs with cloudCode as in the example below.
This is the example:
Adding nodejs to Parse
here is the example code from the link
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var ParseCloud = require('parse-cloud-express');
var Parse = ParseCloud.Parse;
var app = express();
// Host static files from public/
app.use(express.static(__dirname + '/public'));
// Define a Cloud Code function:
Parse.Cloud.define('hello', function(req, res) {
res.success('Hello from Cloud Code on Node.');
});
// Mount the Cloud Code routes on the main Express app at /webhooks/
// The cloud function above will be available at /webhooks/function_hello
app.use('/webhooks', ParseCloud.app);
// Launch the HTTP server
var port = process.env.PORT || 80;
var server = http.createServer(app);
server.listen(port, function() {
console.log('Cloud Code on Node running on port ' + port + '.');
});
console.log(process.env.PORT);
I have imported all the required modules, but still, when I run the server and try to go to the link "127.0.0.1/webhooks/function_hello" I get back Cannot GET /webhooks/function_hello
Any advise?
*OUTPUT when i run the script *
undefined
Cloud Code on Node running on port 80.
UPDATE it seems that with parse's shutdown that they have changed support status for cloudcode which affects integrating it with NodeJs
Had the same issue. GET doesn't work here. You need to make a POST request, and then you'll get {"success":"Hello from Cloud Code on Node."}
Please make sure you are running the right script with node SCRIPT_NAME
It appears your express server is set to port 5000.
See: var port = process.env.PORT || 5000;
Change your URL to http://127.0.0.1:5000/webhooks/function_hello or localhost:5000/webhooks/function_hello and it should appear
If you want to run on the default port (80) you will need to run with sudo for your script and make the following change to the code.
var port = process.env.PORT || 80;
Add a folder to your directory named public. Inside that folder place a file named index.html. Type Hello World in that file, save it. Restart your server. See if you can open http://127.0.0.1/.

EC2 with socket.io

I have set up an aws micro instance for my node application. I use socket.io as well. I am getting the following error:
GET http://localhost:3000/socket.io/1/?t=1393065240268 net::ERR_CONNECTION_REFUSED
in the console at the moment when the socket connection should be created. Apart from this the node app works. I suspect that the GET should not be towards localhost but towards the address of the server.
Note that on the server side node logs that it served socket.io:
debug - served static content /socket.io.js
Here is a picture of the Security Group of my server:
.
Socket.io setup:
env = process.env.NODE_ENV || 'development',
packageJson = require('../package.json'),
http = require('http'),
express = require('express'),
RedisStore = require('connect-redis')(express),
SessionSockets = require('session.socket.io'),
path = require('path'),
settings = require('./settings'),
expose = require('express-expose')
//Configure server for io and session.socket.io
tmpApp = express(),
tmpServer = http.createServer(tmpApp),
io = require('socket.io').listen(tmpServer),
appCookieParser = express.cookieParser(settings.cookie.secret),
appRedisStore = new RedisStore(),
sessionIO = new SessionSockets(io, appRedisStore, appCookieParser)
global.App = {
app: tmpApp,
server: tmpServer,
port: process.env.PORT || 3000,
sessionIO: sessionIO,
io: io,
start: function() {
var setUp = this.util('setUp'),
socketHandler = require('./socketHandler'),
self = this
setUp.initialize(function(err, waitingGames) {
if (err) {
console.log('error at initializing the application')
process.exit(0)
}
if (!self.started) {
self.started = true
self.server.listen(self.port)
socketHandler()
console.log("Running App Version " + App.version + " on port " + App.port + " in " + App.env + " mode")
}
})
},
...
}
UPDATE
When I changed my port to 80 I get a different error:
XMLHttpRequest cannot load http://localhost/socket.io/1/?t=1393067003774. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ec2-54-214-136-70.us-west-2.compute.amazonaws.com' is therefore not allowed access.
I found the problem. It was on the client side. I was connecting to localhost. It's a stupid error, but during development you don't pay attention to these details and it seemed natural that socket.io should connect to the root from where you serve your content.
Since I'm using EC2 and after each restart I get different DNS address I've sent to the page where I'm initializing the socket.io the correct the req.headers.host (using express-expose).

ERR_SSL_PROTOCOL_ERROR browser error message while running a https server in nodejs express

I have a number of nodejs applications running on Express using the code below. They all run fine using code similar to the following:
fs = require 'fs'
https = require 'https'
express = require 'express'
server_port = 3000
keys_dir = 'keys/' server_options = {
key : fs.readFileSync(keys_dir + 'privatekey.pem'),
cert : fs.readFileSync(keys_dir + 'certificate.pem') } app = express.createServer(server_options)
app.listen server_port
console.log "HTTPS Server started on port #{server_port}"
However, when trying to create a new application using this code I see a ERR_SSL_PROTOCOL_ERROR when starting the https server. Any idea what is causing this problem?
I discovered that was caused when moving from express 2.5.8 to express 3 - specifically 3.0.0beta4. When creating a new project the version pulled from npm had changed to the version 3 series. Even though the module is marked as "beta" when you run express --version this version is what is installed now when running npm install express. The details of the changes are outlined here.
To solve this for my case I used the following code:
const fs = require("fs");
const https = require("https");
const express = require("express");
const keysDir = "keys/";
const options = {
key : fs.readFileSync(keysDir + "privatekey.pem"),
ca : fs.readFileSync(keysDir + "certrequest.csr"),
cert : fs.readFileSync(keysDir + "certificate.pem")
};
const app = express();
https.createServer(options, app).listen(3000);

Resources