1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
1

Ошибка: WebSocket connection to 'wss://localhost:8777/' failed: Error in connection establishment: net::ERR_CONNECTION_R

21.04.2019, 17:50. Показов 8815. Ответов 15

Студворк — интернет-сервис помощи студентам
На локальном сервере работает, на нормальном нет.
Без SSL не работало, подключил, тоже не работает.
Javascript
1
var  socket = new WebSocket("wss://localhost:8777");
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
 
    require dirname(__DIR__) . '/vendor/autoload.php';
 
    $server = IoServer::factory(
        new HttpServer(
            new WsServer(
                new Chat()
            )
        ),
        8777
    );
 
    $server->run();
    ?>
Что исправлять? Что менять?
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
21.04.2019, 17:50
Ответы с готовыми решениями:

WebSocket connection failed
WebSocket connection to...

Ошибка Unable to complete network request to host localhost/3050. Failed to establish a connection
Здравствуйте, пытаюсь установить соединение с IB. Добавил компонент IBDatabase1, заполнил поля с...

Ошибка: Database connection through listener failed
Устанавливаю сервер Oracle Database 11g Enterprise x64. Устанавливается без ошибок. Дальше создаю...

Status : Failure -Test failed: Listener refused the connection with the following error: ORA-12505, TNS:listener does not currently know of SID given
listener.ora: SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = PLSExtProc) ...

15
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
22.04.2019, 08:43 2
wss -> ws
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 09:23  [ТС] 3
Dellok, делал, не помогало
0
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
22.04.2019, 09:24 4
на удаленном сервере вы ведь localhost заменяли на адрес, где стоит PHP?
Javascript
1
var  socket = new WebSocket("wss://localhost:8777");
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 09:54  [ТС] 5
Dellok, немного не понял вопрос. Может из-за моей неграмотности. На удалённом сервере этот код и был. Я ничего не менял.
0
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
22.04.2019, 09:56 6
На удаленном сервер надо заменить localhost на адресс, где находиться сам сервер. Либо ИП адресс, либо домен
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 10:04  [ТС] 7
Dellok, сейчас попробую

Добавлено через 4 минуты
Dellok, та же ошибка если пишу "домен:8777", Ошибка 404, если прописываю полный путь.
0
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
22.04.2019, 10:07 8
Где эта ошибка появляется? В консоли разработчика?
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 10:12  [ТС] 9
Dellok, да
0
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
22.04.2019, 10:13 10
покажите скрин ошибки и строку, где инициализируется сокет
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 10:19  [ТС] 11
Dellok, смогу сделать ближе к вечеру. Обязательно скину
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
22.04.2019, 19:10  [ТС] 12
Dellok, изменил путь.
Вылезла другая ошибка. Я даже не знаю что лучше.
Вот новая:
WebSocket connection to 'wss://whitefox.website:8777/whitefox.host/bin' failed: WebSocket opening handshake timed out
Появляется не сразу, а где-то через 30 секунд
0
126 / 93 / 18
Регистрация: 09.01.2011
Сообщений: 466
23.04.2019, 10:16 13
Скорее всего не передается заголовок Upgrade. Больше информации можно найти в интернете по словам websockets Header upgrade
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
25.04.2019, 01:59  [ТС] 14
Dellok, а как его передать или проверить, в чём проблема? В коде всё вроде норм
0
the hardway first
Эксперт JS
2434 / 1815 / 898
Регистрация: 05.06.2015
Сообщений: 3,584
25.04.2019, 09:43 15
White Fox, shared hosting?
0
1 / 1 / 0
Регистрация: 27.12.2018
Сообщений: 53
25.04.2019, 16:56  [ТС] 16
да, но ошибка уже изменилась, может стоит поменять название темы?

Добавлено через 3 часа 46 минут
Короче, я может очень слаб в программировании, но интуиция мне подсказывает, что дело в двух файлах
ClientNegotiator.php:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
namespace Ratchet\RFC6455\Handshake;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use GuzzleHttp\Psr7\Request;
 
class ClientNegotiator {
    /**
     * @var ResponseVerifier
     */
    private $verifier;
 
    /**
     * @var \Psr\Http\Message\RequestInterface
     */
    private $defaultHeader;
 
    function __construct() {
        $this->verifier = new ResponseVerifier;
 
        $this->defaultHeader = new Request('GET', '', [
            'Connection'            => 'Upgrade'
          , 'Upgrade'               => 'websocket'
          , 'Sec-WebSocket-Version' => $this->getVersion()
          , 'User-Agent'            => "Ratchet"
        ]);
    }
 
    public function generateRequest(UriInterface $uri) {
        return $this->defaultHeader->withUri($uri)
            ->withHeader("Sec-WebSocket-Key", $this->generateKey());
    }
 
    public function validateResponse(RequestInterface $request, ResponseInterface $response) {
        return $this->verifier->verifyAll($request, $response);
    }
 
    public function generateKey() {
        $chars     = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyz1234567890+/=';
        $charRange = strlen($chars) - 1;
        $key       = '';
        for ($i = 0; $i < 16; $i++) {
            $key .= $chars[mt_rand(0, $charRange)];
        }
 
        return base64_encode($key);
    }
 
    public function getVersion() {
        return 13;
    }
}
ServerNegotiator.php:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php
namespace Ratchet\RFC6455\Handshake;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Response;
 
/**
 * The latest version of the WebSocket protocol
 * @todo Unicode: return mb_convert_encoding(pack("N",$u), mb_internal_encoding(), 'UCS-4BE');
 */
class ServerNegotiator implements NegotiatorInterface {
    /**
     * @var \Ratchet\RFC6455\Handshake\RequestVerifier
     */
    private $verifier;
 
    private $_supportedSubProtocols = [];
 
    private $_strictSubProtocols = false;
 
    public function __construct(RequestVerifier $requestVerifier) {
        $this->verifier = $requestVerifier;
    }
 
    /**
     * {@inheritdoc}
     */
    public function isProtocol(RequestInterface $request) {
        return $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'));
    }
 
    /**
     * {@inheritdoc}
     */
    public function getVersionNumber() {
        return RequestVerifier::VERSION;
    }
 
    /**
     * {@inheritdoc}
     */
    public function handshake(RequestInterface $request) {
        if (true !== $this->verifier->verifyMethod($request->getMethod())) {
            return new Response(405, ['Allow' => 'GET']);
        }
 
        if (true !== $this->verifier->verifyHTTPVersion($request->getProtocolVersion())) {
            return new Response(505);
        }
 
        if (true !== $this->verifier->verifyRequestURI($request->getUri()->getPath())) {
            return new Response(400);
        }
 
        if (true !== $this->verifier->verifyHost($request->getHeader('Host'))) {
            return new Response(400);
        }
 
        $upgradeSuggestion = [
            'Connection'             => 'Upgrade',
            'Upgrade'                => 'websocket',
            'Sec-WebSocket-Version'  => $this->getVersionNumber()
        ];
        if (count($this->_supportedSubProtocols) > 0) {
            $upgradeSuggestion['Sec-WebSocket-Protocol'] = implode(', ', array_keys($this->_supportedSubProtocols));
        }
        if (true !== $this->verifier->verifyUpgradeRequest($request->getHeader('Upgrade'))) {
            return new Response(426, $upgradeSuggestion, null, '1.1', 'Upgrade header MUST be provided');
        }
 
        if (true !== $this->verifier->verifyConnection($request->getHeader('Connection'))) {
            return new Response(400, [], null, '1.1', 'Connection Upgrade MUST be requested');
        }
 
        if (true !== $this->verifier->verifyKey($request->getHeader('Sec-WebSocket-Key'))) {
            return new Response(400, [], null, '1.1', 'Invalid Sec-WebSocket-Key');
        }
 
        if (true !== $this->verifier->verifyVersion($request->getHeader('Sec-WebSocket-Version'))) {
            return new Response(426, $upgradeSuggestion);
        }
 
        $headers = [];
        $subProtocols = $request->getHeader('Sec-WebSocket-Protocol');
        if (count($subProtocols) > 0 || (count($this->_supportedSubProtocols) > 0 && $this->_strictSubProtocols)) {
            $subProtocols = array_map('trim', explode(',', implode(',', $subProtocols)));
 
            $match = array_reduce($subProtocols, function($accumulator, $protocol) {
                return $accumulator ?: (isset($this->_supportedSubProtocols[$protocol]) ? $protocol : null);
            }, null);
 
            if ($this->_strictSubProtocols && null === $match) {
                return new Response(426, $upgradeSuggestion, null, '1.1', 'No Sec-WebSocket-Protocols requested supported');
            }
 
            if (null !== $match) {
                $headers['Sec-WebSocket-Protocol'] = $match;
            }
        }
 
        return new Response(101, array_merge($headers, [
            'Upgrade'              => 'websocket'
          , 'Connection'           => 'Upgrade'
          , 'Sec-WebSocket-Accept' => $this->sign((string)$request->getHeader('Sec-WebSocket-Key')[0])
          , 'X-Powered-By'         => 'Ratchet'
        ]));
    }
 
    /**
     * Used when doing the handshake to encode the key, verifying client/server are speaking the same language
     * @param  string $key
     * @return string
     * @internal
     */
    public function sign($key) {
        return base64_encode(sha1($key . static::GUID, true));
    }
 
    /**
     * @param array $protocols
     */
    function setSupportedSubProtocols(array $protocols) {
        $this->_supportedSubProtocols = array_flip($protocols);
    }
 
    /**
     * If enabled and support for a subprotocol has been added handshake
     *  will not upgrade if a match between request and supported subprotocols
     * @param boolean $enable
     * @todo Consider extending this interface and moving this there.
     *       The spec does says the server can fail for this reason, but
     * it is not a requirement. This is an implementation detail.
     */
    function setStrictSubProtocolCheck($enable) {
        $this->_strictSubProtocols = (boolean)$enable;
    }
}
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.04.2019, 16:56
Помогаю со студенческими работами здесь

Ошибка: Error connection with SSL
delphi 7, indy 9 Вылезает ошибка подключения к SSL после get запроса к конкретному серверу. На...

Ошибка: Socket error #10060 Connection timeOut
В общем есть обычный FTP клиент на Delphi . Раньше он работал но после переустановки винды на прочь...

nic.ru ошибка Database connection error (2): Could not connect to MySQL
Доброе время суток! Собственно суть в заголовке. Поменял пароль mysql-пользователя, подправил...

Ошибка/исключение Socket Error # 10060 Connection timed out
Всем привет. Ребята подскажите пожалуйста, в чём ошибка выхода данной ошибки/исключения. Если...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
16
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru