Php 如何构建Web套接字连接?
在我的Android项目中,我想实现Web套接字。因此,首先我尝试集成服务器端WebSocket,并尝试在命令行中对其进行测试。下面的链接显示了我如何尝试打开Web套接字连接。我尝试访问在Web套接字连接中创建的端口,它成功了!但是当我附加一条消息时,我从未收到它。可能是因为onMessage函数没有被触发 此外,我还使用以下代码打开Websocket连接并发送消息Php 如何构建Web套接字连接?,php,websocket,ratchet,Php,Websocket,Ratchet,在我的Android项目中,我想实现Web套接字。因此,首先我尝试集成服务器端WebSocket,并尝试在命令行中对其进行测试。下面的链接显示了我如何尝试打开Web套接字连接。我尝试访问在Web套接字连接中创建的端口,它成功了!但是当我附加一条消息时,我从未收到它。可能是因为onMessage函数没有被触发 此外,我还使用以下代码打开Websocket连接并发送消息 ?php ini_set('display_errors',1); use Ratchet\MessageComponentInt
?php
ini_set('display_errors',1);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once '/var/www/vendor/autoload.php';
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
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) {
// The connection is closed, remove it, as we can no longer send it messages
$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();
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8081
);
$server->run();
?>
如果运行php app.php,则不会出现任何错误。那么实际上发送和接收信息应该是有效的吗?此外,onMessage函数似乎没有被触发。但是如果我在公共函数uu构造函数中添加一个echo,它就会被打印出来,因此它可能是唯一执行的函数
我希望有人能帮助我在这个Web套接字连接中接收和打印消息
谢谢你的帮助 websocket是套接字,但套接字不一定是websocket。Telnet不能很好地用于测试WebSocket,因为它连接到套接字,但不进行握手 websocket基本上是一个套接字,它需要在开始发送消息之前进行http握手。这就是为什么棘轮计划看起来没有反应。它在等待你这一方的握手完成 要使它与服务器一起工作,您可能需要在Android端安装websocket客户端。或者,您可以制作一个服务器,它只是一个普通的套接字服务器,而不是websocket 如果您正确地完成了websocket握手,在发送任何消息之前,您应该会看到新的连接!在php端的终端中,由于onOpen函数中的内容 如果您发送了以下内容:
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com
…这可能有用
如果开始执行php app.php,则不会出现错误。函数构造似乎是唯一要触发的函数,它不仅仅是握手。Web套接字是一个完整的协议,有自己的框架系统。