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!
Related
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.
I have created a PHP websocket server script as following.
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
$result = socket_bind($socket, '127.0.0.1', 5001);
while (true) {
$result = socket_listen($socket);
$client = socket_accept($socket);
$input = socket_read($client, 1024);
$output = 'Input Received: '.$input;
socket_write($client, $output, strlen($output));
socket_close($client);
}
socket_close($socket);
I've executed file containing above code in terminal using following command
$ php server.php
Now I want to get the response on my front-end using JavaScript. I've used following JS snippet but not working.
var ws = new WebSocket("ws://localhost:5001/echo");
ws.onopen = function() {
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function() {
alert("Connection is closed...");
};
Receiving following error:
WebSocket connection to 'ws://localhost:5001/echo' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
Writing a PHP websocket server requires to perform a certain handshake with the client connecting to you via ws:// . In addition you need to decode and encode messages going in and out. The real fun starts when the clients contact you via wss://, then you have to take care of certificate and key within your PHP server and use stream-io instead of socket-io and so on and on. You can have a look at my implementation of all this and use it as another starting point .
https://github.com/napengam/phpWebSocketServer
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;
}
}
I've written a short WebSocket example server in PHP yesterday. When the client connects to the server, the server reads the client Handshake and sends the server Handshake back with the appropriate key. onopen() of the client gets fired and the server and client seem to be connected.
My problem is: The server can't receive client messages and the client can't receive server messages. onmessage() wasn't triggered once and socket_select() never gives back the client that sent the message on server side.
function connect() {
try {
var webSocketURL = "ws://" + serverAddress + ":" + serverPort;
socket = new WebSocket(webSocketURL);
socket.onopen = function() {
log("Connected! (" + this.readyState + ")");
}
socket.onclose = function() {
log("Closed! (" + this.readyState + ")");
socket.close();
}
socket.onerror = function(error) {
log("Error: " + error.data);
socket.close();
}
socket.onmessage = function(message) {
log("Message from server: " + message.data);
}
}
catch (e) {
alert("Error: " + e);
}
}
The server code is a bit longer, but you can find it here.
Can anyone tell me what's wrong there? Is the handshake incorrect?
Client output:
Connected! (1)
Message to server: 0USERchannel
Server output.
Help is much appreciated, thank you.
On client side, enshure your socket variable is global.
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.