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

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();
}

Related

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!

Node.js imap connection handling

I need to write a node.js application to keep checking if there is new email from the imap server.
I am trying to write an object handling the imap connection.
var Imap = require('imap'),
inspect = require('util').inspect;
const fs = require('fs');
var MailParser = require("mailparser").MailParser;
var Promise = require("bluebird");
function ImapConnection(config){
if (!(this instanceof ImapConnection))
return new ImapConnection(config);
this._imap = new Imap(config);
this._config = config;
}
ImapConnection.prototype.getImap = function(){
self = this;
if(this._imap.state !== 'authenticated'){
return new Promise(function(resolve,reject){
self._imap.connect();
self._imap.once('ready', function(){
resolve(self._imap);
});
});
}else{
return new Promise(function(resolve,reject){resolve(this._imap);});
}
}
But when I call the object after I called the end() function of the imap object it never connects again and always gives the timeout error:
{ [Error: Timed out while connecting to server] source: 'timeout' }
[connection] Closed
events.js:141
throw er; // Unhandled 'error' event
^
Error: Timed out while connecting to server
at null._onTimeout
(/home/ctw/Documents/nodejsmail/node_modules/imap/lib/Connection.js:280:15)
at Timer.listOnTimeout (timers.js:92:15)
Can anyone tell me what's wrong on my code or any other better practice? Thanks.

Uncaught Error: connect ETIMEDOUT (net.Socket)

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();
});
}

cannot handle net::ERR_CONNECTION_REFUSED in pure js

I use pure js(without JQuery) to send an XMLHttpRequest request to server.
var _xhr = new XMLHttpRequest();
_xhr.open(type, url);
_xhr.setRequestHeader('Content-Type', 'application/json');
_xhr.responseType = 'json';
_xhr.onload = function () {
if (_xhr.status === 200) {
var _json = _xhr.response;
if (typeof _json == 'string')
_json = JSON.parse(_json);
success(_json);
} else {
error(_xhr);
}
};
_xhr.onerror = function(){
console.log('fail');
};
try {
_xhr.send(_to_send);
} catch (e){
options.error(_xhr);
}
when i send a request it's fails(this is ok) and i get an error but I CANNON HANDLE IT. xhr.onerror prints message to console but i get OPTIONS url net::ERR_CONNECTION_REFUSED too. How can I avoid this message in console?
Also i use window.onerror to handle all error but i can not handle this OPTIONS url net::ERR_CONNECTION_REFUSED
This worked for me:
// Watch for net::ERR_CONNECTION_REFUSED and other oddities.
_xhr.onreadystatechange = function() {
if (_xhr.readyState == 4 && _xhr.status == 0) {
console.log('OH NO!');
}
};
This is not limited to just net::ERR_CONNECTION_REFUSED because other network errors (e.g. net::ERR_NETWORK_CHANGED, net::ERR_ADDRESS_UNREACHABLE, net::ERR_TIMED_OUT) may be "caught" this way. I am unable to locate these error messages within the _xhr object anywhere, so making a programmatic decision about which network error has specifically occurred won't be reliable.
There is no way around that error showing in console. Just as if you request a file that does't exist you get a 404 in console, regardless of if you handle the error or not.

Categories

Resources