在我的Android项目中,我想实现Web套接字。因此,首先,我尝试集成服务器端Websocket,并尝试在命令行中对其进行测试。以下链接显示了我如何尝试打开Web套接字连接。我试图到达在Web套接字连接中创建的Port,它起作用了!但是,当我附加一条消息时,我再也收不到。也许是因为未触发onMessage函数?
https://i.stack.imgur.com/N8tsf.jpg
另外,我使用以下代码打开Websocket连接并发送消息。
?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函数。但是,如果我在公共函数__construct()函数中添加回显,则将其打印出来,因此它可能是唯一执行的函数。
我希望有人可以帮助我在此Web套接字连接中接收和打印消息。
感谢您的帮助!
Websocket是一个套接字,但是套接字不一定是Websocket。 Telnet在测试websocket时不能很好地工作,因为它连接到套接字,但是不进行握手。
Websocket本质上是一个套接字,在开始发送消息之前,它首先需要进行HTTP握手。这就是为什么Ratchet程序没有响应的原因。它正在等待握手完成。
要使其与服务器一起使用,您可能希望在Android方面获得一个Websocket客户端。或者,您可以将服务器配置为普通的套接字服务器,而不是websocket。
如果您正确完成了websocket握手,则在发送任何消息之前,由于onOpen函数的功能,您应该在php端的终端中看到New connection!
。
如果您发送的内容与此类似:
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
...可能有效。