Uncaught Error: connect ETIMEDOUT (net.Socket) - javascript

I am trying to send text to my network printer via tcp connection.
function print(buf2){
var printer = new net.Socket();
printer.connect(printer_port, printer_name, function() {
console.log('Connected');
printer.write(buf2);
printer.end()
});
}
Everything works fine, but after some time my application throws me the error Uncaught Error: connect ETIMEDOUT and it doesn't connect with my printer.
To fix it, I open a browser and navigate to my printers address(192.168.1.111) and then my application connects again but after some time it stops connecting and throws the same error (Uncaught Error: connect ETIMEDOUT).
The applications is written with electron and i use the net npm
var net = require('net');
In my application every 3 seconds i call a get request and then i call the print method
function proxy() {
var client = new HttpClient();
client.get('my_link', function(response) {
var jsonItem = JSON.parse(response)
if(jsonItem.items.length > 0)
{
var text_to_print = jsonItem.items[0].text
print(text_to_print,text_id);
}
Any suggestions what could cause this error?

This should help you to debug.
function print(printer_port, printer_name, buf2) {
var printer = net.createConnection(printer_port, printer_name, function () {
//'connect' listener
console.log("Connected!");
printer.end(buf2);
});
printer.setTimeout(60 * 1000); //1 minute
printer.on("end", function () {
console.log("Disconnected from server!");
});
printer.on("timeout", function () {
console.log("Timeout!");
printer.destroy();
});
}

Related

Failed to construct 'WebSocket': The URL '{{.}}' is invalid

gorilla/websocket example
In this example:
https://github.com/gorilla/websocket/blob/e8629af678b7fe13f35dff5e197de93b4148a909/examples/echo/server.go#L79
The WebSocket is created by:
ws = new WebSocket("{{.}}");
The example works fine.
Problem
But, then I want to use the same code in another JS code like:
var ws;
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
console.log("OPEN SOCKET");
}
ws.onclose = function(evt) {
console.log("CLOSE SOCKET");
ws = null;
}
ws.onmessage = function(evt) {
console.log("RESPONSE SOCKET: RECEIVED");
}
ws.onerror = function(evt) {
console.log("ERROR: " + evt.data);
}
ws.send(positions);
ws.close();
I'm getting this error:
Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The URL '{{.}}' is invalid.
at AddObjectCommand.execute
I changed WebSocket like this:
ws = new WebSocket("ws://127.0.0.1:8080/echo");
But I'm still getting an error:
WebSocket connection to 'ws://127.0.0.1:8080/echo' failed: Error during WebSocket handshake: Unexpected response code: 403
I cannot figure out what I'm doing wrong. What did I miss?
Fix 403
The 403 error got resolved by this suggestion:
https://github.com/gorilla/websocket/issues/367#issuecomment-375971418
By adding:
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
Before:
c, err := upgrader.Upgrade(w, r, nil)
It's not safe to trust all origins, of course. Just a temporary fix.
Yet another error
But another error is thrown:
Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
The error of:
Uncaught (in promise) DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.
Got resolved by sending data through WebSocket, by its .onopen callback:
var positions = ...
var ws;
ws = new WebSocket("ws://127.0.0.1:8080/echo");
ws.onopen = function(evt) {
console.log("OPEN SOCKET");
console.log("SEND: START");
ws.send(positions);
ws.close();
}

Javascript Websocket fails to receive TCP data

I'm trying to receive json data from an ESP32 via TCP to a website hosted thru WAMP (localhost -> ESP32 IP address on local network is 10.11.125:23). Below is my javascript function. My browser (Firefox Developer) generates a "SecurityError: The operation is insecure" when executing the line var connection = new webSocket('ws://10.11.13.125:23'). What am I missing??
function openWebsocket() {
console.log("open Websocket.....");
var connection = new WebSocket('ws://10.11.13.125:23');
connection.onerror = function(error) {
$("#Connection").html("Connection Error");
console.log("Websocket Error: " + error);
}
connection.onopen = function(evt) {
$("#Connection").html("Connected");
}
connection.binaryType = 'arraybuffer';
connection.onmessage = function(evt) {
console.log("Server: " + evt.data.byteLength);
}
console.log("ReadyState: "+connection.readyState);
}
I found the problem. The Chromium browser yields a more descriptive error message. Port 23 is not available. Switched over to
var connection = new WebSocket('ws://10.11.13.125:80');
and voila, everything works as expected.
Sorry for posting about an issue that in the end I found the solution for myself.

Javascript websocket wont connect to php websocket

So I've been trying to get this whole connection between PHP socket server and Javascript websockets working, but I cant get them to connect. I have looked everywhere to figure out what I'm doing wrong. My guess is it's the protocol but I have no idea. Everything helps, comment if you have questions.
Client-Side Example
<script>
var connection = new WebSocket('ws://127.0.0.1:4446');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
// Log errors
connection.onerror = function (error){
console.log('WebSocket Error ' + error);
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ' + e.data);
};
</script>
Server-Side Example -PHP
<?php
$conn = stream_socket_server('tcp://127.0.0.1:4446');
while ($socket = stream_socket_accept($conn)) {
$pkt = stream_socket_recvfrom($socket, 1500, 0, $peer);
if (false === empty($pkt)) {
stream_socket_sendto($socket, $pkt, 0, $peer);
}
fclose($socket);
usleep(10000); //100ms delay
}
stream_socket_shutdown($conn, \STREAM_SHUT_RDWR);
?>
Console Log Error
VM4666:35 WebSocket connection to 'ws://127.0.0.1:4446/' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
I understand that there are many questions on here similar but I cant seem to find a solution, I appreciate any help!

How to handle invalid URL / IP's in websockets?

I'm using HTML / Javascript web sockets to communicate with a python server program. Now I have the option to change the server's IP via clean UI and I have a .onerror function that handles with connection errors, however this doesn't handle initial errors. What I mean by this is if I were to enter a completely invalid address, it wont even attempt to connect with it (which is fine) and spit out and error like: [Error] WebSocket network error: The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.). How can I handle this error so I can say, popup a message for example?
Here's a brief overview of my JS script.
function updateDevice(id, ipUI){
if ("WebSocket" in window){
var ws = new WebSocket(serverIP);
// Here is where I need to handle the bad address right?
ws.onopen = function(){
ws.send(id);
};
ws.onmessage = function (evt){
var received_msg = evt.data;
};
// This function ws.onerror doesnt handle bad addresses.
ws.onerror = function(){
document.getElementById("error_msg").style.display='block';
};
}else{
alert("This site doesnt support your browser...");
};
};
You could wrap the new WebSocket in a try/catch:
try {
new WebSocket(serverIP);
} catch (e) {
if (e instanceof DOMException) {
alert('Invalid address!');
} else {
throw e;
}
}

Unhandled ''error'' event in Node.JS

I'm trying to active an RFID reader through node.js and then send the tag back.
It works great. It reads the tag, responds with an ID, then send the ID to the pinging node client.
However, every time the node.JS program picks up a set of data from an RFID tag, after it sends, it closes down with the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: EBADF, read
This causes the node process to quit all the time. What could be the problem here?
My code is the following;
// Socket.io server details
var io = require('socket.io').listen(3000);
// Serialport plugin declared and made a serialport variable
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
// Variable containing technical USB port details
var serialPort = new SerialPort("/dev/ttyUSB0",
{baudrate: 2400, parser: serialport.parsers.readline("\n")},
false); // this is the openImmediately flag [default is true]
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.on('ping', function (data) {
serialPort.open(function () {
// Open notification
console.log('open');
//Start listening
serialPort.on('data', function(data) {
// If content is empty, filter out
if (data.trim() !== '') {
line = data;
//Execute function again, get tag, handle tag and end process
serialPort.close(function () {
console.log('De uiteindelijke tag is ' + data);
console.log('Ping received with data: ' + data);
socket.emit('pong', data);
console.log('closing');
});
console.log('hallo');
}
});
});
});
});
Add a listener to handle the error in the serial port, like the code below:
serialPort.on('error', function(error) {
console.log('The error: '+error);
//...
});

Categories

Resources