PHP使用websocket来实现实时传输出现了问题,原本服务器客户端代码都在本地,可以连接上并能发送消息。后面将服务器代码放在云服务器上运行,本地去连接,结果连接不上了。
websocket是依赖Ratche框架实现的,端口我也开放了,就是不知道哪里处了问题,请各位解答。
附上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
</head>
<body>
<input id="message" type="text">
<button id="send">Send</button>
<hr>
<div id="timeline"></div>
<script>
// 设定URL建立WebSocket连接
var conn = new WebSocket('ws://服务器地址:25252/chat');
// 成功建立连接
conn.onopen = function (e) {
conn.send('1,Hello!');
// alert('WebSocket connection ok.');
};
// 收到消息
conn.onmessage = function (e) {
document.getElementById('timeline').innerText += e.data;
document.getElementById('timeline').innerHTML += '<br>';
};
// 连接出错
conn.onerror = function (e) {
alert('WebSocket connection error.');
}
// 断开连接
conn.onclose = function (e) {
alert('WebSocket connection closed.');
}
// 发送消息
document.getElementById('send').onclick = function () {
if (!document.getElementById('message').value) return;
conn.send(document.getElementById('message').value);
document.getElementById('message').value = '';
}
</script>
</body>
</html>
<?php
namespace app\api\controller;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\App;
require_once '/www/wwwroot/yxt_test/vendor/autoload.php';
// header("Access-Control-Allow-Origin: *");
// header("Access-Control-Allow-Headers: *");
/**
* 私聊模型
*/
class MyChat implements MessageComponentInterface {
// 用于保存客户端信息
protected $clients;
protected $clientsUserIds;
public function __construct() {
// 新建SplObjectStorage用于保存对象
$this->clients = new \SplObjectStorage;
$this->clientsUserIds = [];
}
// $conn是要与服务端建立连接的客户端对象
public function onOpen(ConnectionInterface $conn) {
// 向$clients添加建立连接的客户端
$this->clients->attach($conn);
$this->clientsUserIds[$conn->resourceId] = $conn;
// 输出提示,resourceId可以用于标识客户端
echo "New connection! Id: {$conn->resourceId}\n";
}
public function onClose(ConnectionInterface $conn) {
if (isset($this->clientsUserIds[$conn->resourceId])) {
unset($this->clientsUserIds[$conn->resourceId]); // 从映射中删除用户 ID
}
// 将关闭连接的客户端从$clients中删除
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
// $msg是客户端发送的数据
public function onMessage(ConnectionInterface $from, $msg) {
// 假设消息格式是: {"target_id": "targetId", "message": "your message"}
// $data = json_decode($msg, true);
$data = explode(',',$msg);
$to = $data[0];
echo $to."\n";
// print_r($this->clientsUserIds[$to]);
$content = $data[1];
// 遍历所有客户端,转发消息
if($content&&isset($this->clientsUserIds[$to]))
$this-> clientsUserIds[$to]->send("Client {$from->resourceId} to {$to}: {$content}");
else if($content)
{
$from ->send("Client {$from->resourceId} to {$from->resourceId}: {$content}");
}
else
echo " message is null && user no exsit";
// foreach ($this->clients as $client) {
// $client->send("Client {$from->resourceId}: {$msg}");
// // 也可以选择不转发给发送者自己
// // if ($from !== $client) {
// // $client->send("Client {$from->resourceId}: {$msg}");
// // }
// }
echo "Client {$from->resourceId}: {$msg}\n";
}
}
class WebSocketServer {
public function run() {
echo "Server is running...\n";
// 在本机的25252端口启动Ratchet应用
$app = new App('服务器地址', 25252);
// 将上面的留言板应用与 `/chat` 路径关联
$app->route('/chat', new MyChat, array('*'));
// 启动应用
$app->run();
}
}
// 启动WebSocket服务器
(new WebSocketServer())->run();