J
J
jenya_zhilin2021-08-06 07:06:39
PHP
jenya_zhilin, 2021-08-06 07:06:39

How to fix an error when connecting a site to a server on web sockets?

Good day! I'm learning web sockets, wrote a simple server in PHP using Workerman. The server starts successfully without any errors. Next, I wrote a banal code for a connection test on web sockets using pure JS. But then I ran into something incomprehensible, when I load the page, a connection is immediately established with a web socket, the following is displayed in the Workerman logs:
610cb48e1ad56761603373.png

Well, accordingly, an error occurs in JS that the connection failed (WebSocket connection to _name_site_ failed).
That is, it turns out that at first the connection was established, then it was disconnected, and so on again.

Code sources:

Server in PHP (Workerman):

<?php

use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker("websocket://0.0.0.0:2346");
$worker->count = 4;

$worker->onConnect = function($c) {
    echo "Connected\n";
};

$worker->onMessage = function($c, $data) use ($worker) {
    foreach ($worker->connections as $clientConnections) {
        $clientConnections->send($data);
    }
};

$worker->onClose = function($c) {
    echo "Connection closed\n";
};

Worker::runAll();


JS client:

<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
            const socket = new WebSocket("wss://176.99.11.138:2346");
    </script>
</body>
</html>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question