我是websocket的新手。我试着做一个简单的聊天应用程序,我跟着棘轮你好世界教程。我用
在本地运行它'ws://localhost:8080'
它完美无缺。我可以通过javascript控制台聊天,就像教程说的那样。现在,我尝试将其放在我的网络服务器上 https://some.domain.co/websocket 。我试过做同样的事情,比如
'ws://some.domain.co:8080'
'ws://some.domain.co:8080/websocket'
'ws://some.domain.co/websocket:8080'
'wss://some.domain.co:8080'
'wss://some.domain.co:8080/websocket'
'wss://some.domain.co/websocket:8080'
但它们都不起作用。通过浏览器仍然给出错误
与'wss://some.domain.co/'的WebSocket连接失败:错误期间 WebSocket握手:意外的响应代码:200
或
与'wss://some.domain.co:8080 /'的WebSocket连接失败:连接建立错误:net :: ERR_TIMED_OUT
我想我的网址有问题。有什么建议?先谢谢
修改
chatServer.php
require dirname(__DIR__) . '/vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
include("Chat.php");
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
), 8080
);
$server->run();
Chat.php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
echo "Server is Running\n";
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
, $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver, send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}