Matin B.
Matin B.

Reputation: 405

JS WebSocket, Problem with making a connection to the Server

I just wanted to test WebSockets, so I searched for them and found some tutorials. Then, I wrote some code in PHP for creating a WebSocket Server. After that, I created a client HTML file that tries to send data to the WebSocket Server file via creating a connection. Now, the problem I have is that I don't know what the hostname in the HTML client file should be (It gives me an error).

My WebSocket PHP Server file contains the following:

<?php
$host = "192.168.xxx.xx";
$port = 8080;
set_time_limit(0);

$sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Couldn't create socket.");
$result = socket_bind($sock, $host, $port) or die("Couldn't bind to socket.");

$result = socket_listen($sock, 3) or die("Couldn't set up socket listener.");

do {
    $accept = socket_accept($sock) or die("Couldn't accept incoming connection.");
    $msg = socket_read($accept, 1024) or die("Couldn't read input.");
    $msg = trim($msg);

    $reply = "Message from server";
    socket_write($accept, $reply, strlen($reply)) or die("Couldn't write output.");
} while (true);

socket_close($accept, $sock);
?>

And my HTML client file contains:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>WebSocket</title>
    </head>
    <body>
        <input type="text" name="msg" id="msg">
        <button id="sendbtn">Send</button>

        <script>
        const socket = new WebSocket('ws://192.168.xxx.xx:8080/');

        socket.addEventListener('open', function(event){
            console.log("Socket was created.");
        });

        document.getElementById("sendbtn").addEventListener('click', function(){

            socket.send(document.getElementById("msg").value);

        });
    
        socket.addEventListener('message', function(event){
            alert(event.data);
        });
        </script>
    </body>
</html>

These two files are placed together in a folder (which is the DocumentRoot).

Any help is appreciated.

Upvotes: 1

Views: 418

Answers (1)

Matin B.
Matin B.

Reputation: 405

According to what user @ADyson said in the comments, a simple TCP connection can't be used for creating a WebSocket Server. Instead, Ratchet WebSocket Server can be used.

Upvotes: 1

Related Questions