Quantcast
Channel: Active questions tagged https - Stack Overflow
Viewing all articles
Browse latest Browse all 1580

Websockets not working on WSS over https but works fine with ws over http

$
0
0

I am creating a function to interact with multiple projects.There are two projects in one there are applications to fill and in another project, all application response can be seen.I wanted to implement a function to update the application response whenever someone fills the application, for this task I wanted to use WebSockets to interact between project and update(append with new response) page whenever I get msg from WebSockets.

Now while connecting with WebSockets over https and wss I'm not able to connect and getting an error like "ERR_SSL_PROTOCOL_ERROR" But works fine when I use ws to connect over http.I'm using a self-signed certificate on localhost.

<?phprequire_once 'Autoloader.php';use Workerman\Worker;use Workerman\Connection\AsyncTcpConnection;// массивдлясвязисоединенияпользователяинеобходимогонампараметра$users = [];// создаёмлокальный tcp-сервер, чтобыотправлятьнанегосообщенияизкоданашегосайта$tcp_worker = new Worker("tcp://127.0.0.1:1234");// создаёмобработчиксообщений, которыйбудетсрабатывать,// когданалокальный tcp-сокетприходитсообщение$tcp_worker->onMessage = function($connection, $data) use ($tcp_worker){    // пересылаемсообщениевовсеостальныесоединения - это 4 ws-сервера, кодкоторыхбудетниже    foreach ($tcp_worker->connections as $id => $webconnection) {        if ($connection->id != $id) {            $webconnection->send($data);        }    }};$context = array('ssl' => array('local_cert' => '/private/etc/apache2/ssl/localhost.pem','local_pk'   => '/private/etc/apache2/ssl/localhost.key',    ));// Create a Websocket server with ssl context.$ws_worker = new Worker("websocket://0.0.0.0:8000", $context);// создаём ws-сервер, ккоторомубудутподключатьсявсенашипользователи// $ws_worker = new Worker("websocket://0.0.0.0:8000");$ws_worker->count = 4;// создаёмобработчик, которыйбудетвыполнятьсяпризапускекаждогоиз 4-х ws-серверов$ws_worker->onWorkerStart = function() use (&$users){    //подключаемсяизкаждогоэкземпляра ws-сервераклокальному tcp-серверу    $connection = new AsyncTcpConnection("tcp://0.0.0.0:1234");    $connection->onMessage = function($connection, $data) use (&$users) {        $data = json_decode($data);        // отправляемсообщениепользователюпо userId        if (isset($users[$data->user])) {            $webconnection = $users[$data->user];            $webconnection->send($data->message);        }    };    $connection->connect();};$ws_worker->onConnect = function($connection) use (&$users){    $connection->onWebSocketConnect = function($connection) use (&$users)    {        // приподключенииновогопользователясохраняем get-параметр, которыйжесамиипередалисостраницысайта        $users[$_GET['user']] = $connection;        // вместо get-параметраможнотакжеиспользоватьпараметриз cookie, например $_COOKIE['PHPSESSID']    };};$ws_worker->onClose = function($connection) use(&$users){    if(isset($users[$connection->uid]))    {        // удаляемпараметрприотключениипользователя        unset($users[$connection->uid]);    }};// Run workerWorker::runAll();

Front-end Code

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><script>        ws = new WebSocket("wss://127.0.0.1:8000/?user=tester01");        ws.onmessage = function(evt) {alert(evt.data);};</script></head></html></source>

Viewing all articles
Browse latest Browse all 1580

Trending Articles