问题描述
我是 websockets 的新手,我想在我的 Laravel 应用程序中实现这样的服务。 我已经阅读了几个关于这个主题的帖子/页面,但没有一个解释我需要做什么。他们都展示了如何创建一个“Echo”websocket 服务器,其中服务器只响应从客户端收到的消息,这不是我的情况。
作为起始基础,我使用了以下提供的代码:
从命令行或其他控制台运行 websocket 服务器的位置。服务器有自己的类来定义它并导入 WebSocketController 类(MessageComponentInterface),其中包含经典的 WebSocket 服务器事件(onopen、onMessage、onClose、onError)。
一切正常,但是,我如何“告诉”WebSocket 服务器从另一个类(也属于另一个命名空间)向特定连接(客户端)发送消息?这是通知或事件的情况,其中必须将新的 Web 内容发送到该特定客户端。来自客户端的途中没有订阅或发布。
正如@Alias 在他的帖子 Ratchet PHP - Push messaging service 中所问的那样,我显然无法创建 Websocket 服务器或其事件管理类的新实例,那么向客户端发送内容或消息的最佳方法是什么?>
正如你们所看到的,通信只有一种方式:从 WebSocket 服务器到客户端,而不是相反。 我已经为此准备了一个通知类和一个侦听器类,但是,我仍然不知道如何通过 handle() 方法解决与客户端的通信:
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Events\NotificationSent;
use Illuminate\Queue\InteractsWithQueue;
class LogNotification
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param NotificationSent $event
* @return void
*/
public function handle(NotificationSent $event)
{
// Can content or message be sent to the client from here? how?
}
}
解决方法
好吧,经过大量学习和研究,我可以在以下位置发布类似问题的答案:
How to send a message to specific websocket clients with symfony ratchet?
这是我找到的解决方案,根据我在该线程的第二条评论中写的内容。
我使用 composer 为 websocket 服务器安装了 cboden/Ratchet 包。 我需要在后端触发事件时向用户/用户组发送通知,或更新 UI。
我所做的是:
1) 使用 composer 安装了 amphp/websocket-client 包。
2) 创建了一个单独的类来实例化一个可以连接到 websocket 服务器的对象,发送所需的消息并断开连接:
namespace App;
use Amp\Websocket\Client;
class wsClient {
public function __construct() {
//
}
// Creates a temporary connection to the WebSocket Server
// The parameter $to is the user name the server should reply to.
public function connect($msg) {
global $x;
$x = $msg;
\Amp\Loop::run(
function() {
global $x;
$connection = yield Client\connect('ws://ssa:8090');
yield $connection->send(json_encode($x));
yield $connection->close();
\Amp\Loop::stop();
}
);
}
}
3) onMessage()
事件,在 webSocket 服务器的处理程序类中,如下所示:
/**
* @method onMessage
* @param ConnectionInterface $conn
* @param string $msg
*/
public function onMessage(ConnectionInterface $from,$msg) {
$data = json_decode($msg);
// The following line is for debugging purposes only
echo " Incoming message: " . $msg . PHP_EOL;
if (isset($data->username)) {
// Register the name of the just connected user.
if ($data->username != '') {
$this->names[$from->resourceId] = $data->username;
}
}
else {
if (isset($data->to)) {
// The "to" field contains the name of the users the message should be sent to.
if (str_contains($data->to,',')) {
// It is a comma separated list of names.
$arrayUsers = explode(",",$data->to);
foreach($arrayUsers as $name) {
$key = array_search($name,$this->names);
if ($key !== false) {
$this->clients[$key]->send($data->message);
}
}
}
else {
// Find a single user name in the $names array to get the key.
$key = array_search($data->to,$this->names);
if ($key !== false) {
$this->clients[$key]->send($data->message);
}
else {
echo " User: " . $data->to . " not found";
}
}
}
}
echo " Connected users:\n";
foreach($this->names as $key => $data) {
echo " " . $key . '->' . $data . PHP_EOL;
}
}
如您所见,您希望 websocket 服务器将消息发送到的用户在 $msg 参数中指定为字符串 ($data->to) 以及消息本身 ($data- > 消息)。这两件事是 JSON 编码的,因此参数 $msg 可以被视为一个对象。
4) 在客户端(布局刀片文件中的 javascript),当客户端连接时,我将用户名发送到 websocket 服务器:
var currentUser = "{{ Auth::user()->name }}";
socket = new WebSocket("ws://ssa:8090");
socket.onopen = function(e) {
console.log(currentUser + " has connected to websocket server");
socket.send(JSON.stringify({ username: currentUser }));
};
socket.onmessage = function(event) {
console.log('Data received from server: ' + event.data);
};
因此,用户名及其连接号保存在 websocket 服务器中。
5) 处理程序类中的 onOpen()
方法如下所示:
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients[$conn->resourceId] = $conn;
echo " \n";
echo " New connection ({$conn->resourceId}) " . date('Y/m/d h:i:sa') . "\n";
}
每次客户端连接到 websocket 服务器时,它的连接号或资源 ID 都存储在一个数组中。这样,用户名存储在一个数组 ($names) 中,而键存储在另一个数组 ($clients) 中。
6) 最后,我可以在我的项目中的任何位置创建 PHP websocket 客户端 (wsClient) 的实例,以将任何数据发送给任何用户:
public function handle(NotificationSent $event) {
$clientSocket = new wsClient();
$clientSocket->connect(array('to'=>'Anatoly,Joachim,Caralampio','message'=>$event->notification->data));
}
在本例中,我使用的是通知事件侦听器的 handle() 方法。
好的,这适用于想知道如何从 PHP websocket 服务器(也称为回显服务器)向一个特定客户端或一组客户端发送消息的任何人。