当前位置: 首页 > 工具软件 > PHP WebSocket > 使用案例 >

php如何发送数据给websocket,如何向特定用户发送消息Ratchet PHP Websocket

松洛华
2023-12-01

基本上你需要一个语法来发送数据到WebSocket,我建议使用 JSON 对象来做到这一点.在您的WebSocket类中,您需要一个名为subscriptions的局部变量和一个名为users的局部变量.

namespace MyApp;

use Ratchet\MessageComponentInterface;

use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface

{

protected $clients;

private $subscriptions;

private $users;

public function __construct()

{

$this->clients = new \SplObjectStorage;

$this->subscriptions = [];

$this->users = [];

}

public function onOpen(ConnectionInterface $conn)

{

$this->clients->attach($conn);

$this->users[$conn->resourceId] = $conn;

}

public function onMessage(ConnectionInterface $conn, $msg)

{

$data = json_decode($msg);

switch ($data->command) {

case "subscribe":

$this->subscriptions[$conn->resourceId] = $data->channel;

break;

case "message":

if (isset($this->subscriptions[$conn->resourceId])) {

$target = $this->subscriptions[$conn->resourceId];

foreach ($this->subscriptions as $id=>$channel) {

if ($channel == $target && $id != $conn->resourceId) {

$this->users[$id]->send($data->message);

}

}

}

}

}

public function onClose(ConnectionInterface $conn)

{

$this->clients->detach($conn);

unset($this->users[$conn->resourceId]);

unset($this->subscriptions[$conn->resourceId]);

}

public function onError(ConnectionInterface $conn, \Exception $e)

{

echo "An error has occurred: {$e->getMessage()}\n";

$conn->close();

}

}

?>

与之相关的 javascript 看起来有点像这样

var conn = new WebSocket('ws://localhost:8080');

conn.onopen = function(e) {

console.log("Connection established!");

};

conn.onmessage = function(e) {

console.log(e.data);

};

function subscribe(channel) {

conn.send(JSON.stringify({command: "subscribe", channel: channel}));

}

function sendMessage(msg) {

conn.send(JSON.stringify({command: "message", message: msg}));

}

注意:这段代码是未经测试的,我是根据我对Ratchet的经验编写的.祝好运 :)

 类似资料: