Javascript Websocket fails to receive TCP data - javascript

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.

Related

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!

WebSocket - Javascript client says connected, but Java server doesn't

I have very simple code, yet, it doesn't work perfectly.
In Java server it just says Hello and Bye when opening and closing a connection and prints a sent message:
#ApplicationScoped
#ServerEndpoint("/tictactoe")
public class WebSocketServer {
private Logger logger = Logger.getLogger(this.getClass().getName());
#OnOpen
public void open(Session session) {
logger.info("WebSocket: Hello - " + session.getId());
}
#OnClose
public void close(Session session) {
logger.info("WebSocket: Farewell - " + session.getId());
}
#OnMessage
public void messageHandler(String message, Session session) {
logger.info("WebSocket: New Message - " + message);
}
}
In JavaScript it does pretty much the same like in the server and sends a message when clicking a button:
var socket = new WebSocket("ws://localhost:8080/TicTacToeZTP/tictactoe");
socket.onopen = function (event) {
console.log("WebSocket: Connected");
console.log("WebSocket: " + checkConnection(socket.readyState));
};
socket.onclose = function (event) {
console.log("WebSocket: Disconnected");
};
socket.onerror = function(event) {
console.log("WebSocket: Error");
};
socket.onmessage = function (event) {
console.log("WebSocket: New Message - " + event.data);
};
function checkConnection(readyState) {
switch(readyState){
case 0: return "CONNECTING";
case 1: return "OPEN";
case 2: return "CLOSING";
case 3: return "CLOSED";
default: return "UNDEFINED";
}
}
$("#send").click(function () {
var msg = {
type: "message",
text: "zaladzi"
};
socket.send(JSON.stringify(msg));
});
Now its time for a problem. After refreshing a page with an established connection.
What the script says:
WebSocket: Connected
WebSocket: OPEN
But the server doesn't open a new one. In fact I sometimes need a couple of refreshes to open a new connection on the server.
What the server says:
Info: WebSocket: Hello - 29538711-f815-4c59-835e-97aaaac1d112
Info: WebSocket: Farewell - 29538711-f815-4c59-835e-97aaaac1d112
I'm using Payara 4.1 server. How to solve this issue?
TL/DR JavaScript client says connection is opened, but Java client says there is no such a connection.
This is likely due to a bug in Payara Server which is fixed https://github.com/payara/Payara/issues/536 in that bug OnOpen isn't called in the server when a socket is reused.
You could try a pre-release version of Payara to ensure it is fixed. Pre-release builds are available from the Payara website a new pre-release build is created and uploaded every time their Jenkins CI server completes a GitHub merge build.

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

Meteor.http.get request -> Error: Hostname/IP doesn't match certificate's altnames

I'm trying to use meteor.http module and I'm getting the following error on the server side.
"Error: Hostname/IP doesn't match certificate's altnames" since I'm new in Meteor and in Node.js and its javaScript debugging is hard (btw how can I debug server side scripts ? client side it's easy), I'm using MAC OS X 10.9 not sure if it's relevent...
Thanks
Ronen
client side code:
'click #buildButton' : function () {
console.log("Jenkins job request");
$('#buildButton').attr('disabled','true').val('loading...');
var userName = "Ronen";
Meteor.call('jenkinsServiceBuild', function(err, respJson) {
if(err) {
window.alert("Error: " + err.reason);
console.log("error occured on receiving data on server. ", err );
} else {
window.alert("Success: ");
console.log("respJson: ", respJson);
//window.alert(respJson.length + ' tweets received.');
Session.set("recentTweets",respJson);
}
$('#buildButton').removeAttr('disabled').val('build');
});
}
Server Side Code:
Meteor.methods({jenkinsServiceBuild: function(userName) {
var url = "https://www.ynet.co.il";
//synchronous GET
var result = Meteor.http.get(url, {timeout:30000});
if(result.statusCode==200) {
var respJson = JSON.parse(result.content);
console.log("response received.");
return respJson;
} else {
console.log("Response issue: ", result.statusCode);
var errorJson = JSON.parse(result.content);
throw new Meteor.Error(result.statusCode, errorJson.error);
}
}
});
The site 'https://www.ynet.co.il' has an incorrectly installed SSL certficate for that domain. It's using akamai's certificate.
If you know and trust the site and its for nothing too secure just remove the s in https
var url = "http://www.ynet.co.il";
Also I'm not sure the code will work, looking at the site it serves html content but this line:
var respJson = JSON.parse(result.content);
Suggests it serves JSON content. If it does server json content use this instead:
var respJson = result.data;

WebSockets Handshake not working

Im trying to get a connection between a JavaScript WebSocket and a TCP Server/Client applicat written in VisualBasic .Net . My problem is that the handshake fails. I do get a handshake request from the local website, but it does not accept my response.
The code of the JavaScript file:
<script type="text/javascript">
var ws;
function connect() {
if("WebSocket" in window) {
debugger;
ws = new WebSocket("ws://192.168.193.178:1925");
ws.onopen = function() {
alert("Connection established");
};
ws.onmessage = function(evt) {
var received_msg = evt.data;
alert("Message is received: " + received_msg);
};
ws.onerror = function(evt) {
alert("Error");
var received_msg = evt.data;
alert("Error: " + received_msg);
};
ws.onclose = function() {
// websocket is closed.
alert("Connection closed");
};
//ws.send("Test");
//ws.close();
} else {
alert("WebSocket NOT supported by your Browser!");
}
}
function disconnect() {
ws.close();
}
function send(message) {
ws.send(message);
alert("Sent: " + message);
}
</script>
The VB.Net code output:
Received:
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 192.168.193.178:1925
Origin: http://127.0.0.1:8020
Sec-WebSocket-Key: eGzO0afUD5jCeUdzdoxwjw==
Sec-WebSocket-Version: 13
Sent:
HTTP/1.1 101 Web Socket Protocol Handshake\r\n
Upgrade: WebSocket\r\n
Connection: Upgrade\r\n
Sec-WebSocket-Origin: null\r\n
Sec-WebSocket-Accept: NzU3M2IwYzk0ZWFmYjg4MzMyZWI1ODhhZWI4NWUyZDE1YWU2YzhlNA==\r\n
\r\n
I just cant get the WebSocket to accept the handshake, I hope anyone can help me out.
Maybe the hash-generation contains errors?
Edit:
I now get the correct Sec-WebSocket-Accept String (dXOwyU6vuIMy61iK64Xi0VrmyOQ=), anyway the WebSocket seems not to handle the handshake response. I tried debugging it with the Chrome Developer Tools, but I don't get usefull information from it. Any tips?
One thing sticks out immediately. The Sec-WebSocket-Accept value in the server response is much longer than what a correct value looks like. In fact, the correct value for that Key should be "dXOwyU6vuIMy61iK64Xi0VrmyOQ=". My guess is you're doing the base-64 encoding on the string representation of the SHA1 result. The encoding should be done on the byte representation of SHA1 result.

Categories

Resources