我正在尝试构建通知消息系统.我正在使用SimpleWsServer.php服务器示例.我想在服务器上完成任务时将通知推送到用户的浏览器.这需要使用PHP完成,我无法找到显示它的教程.当PHP服务器作为管理器运行时,所有教程似乎都显示了发送和接收的tavendo / AutobahnJS脚本.
是否可以使用php脚本向订阅者发送消息?
解决方法:
天文,
这实际上非常简单,可以通过几种不同的方式完成.我们设计了Thruway客户端来模仿AutobahnJS客户端,因此大多数简单示例都将直接翻译.
我假设你想从一个网站发布(不是一个长期运行的PHP脚本).
在您的PHP网站中,您需要执行以下操作:
$connection = new \Thruway\Connection(
[
"realm" => 'com.example.astro',
"url" => 'ws://demo.thruway.ws:9090', //You can use this demo server or replace it with your router's IP
]
);
$connection->on('open', function (\Thruway\ClientSession $session) use ($connection) {
//publish an event
$session->publish('com.example.hello', ['Hello, world from PHP!!!'], [], ["acknowledge" => true])->then(
function () use ($connection) {
$connection->close(); //You must close the connection or this will hang
echo "Publish Acknowledged!\n";
},
function ($error) {
// publish failed
echo "Publish Error {$error}\n";
}
);
});
$connection->open();
而javascript客户端(使用AutobahnJS)将如下所示:
var connection = new autobahn.Connection({
url: 'ws://demo.thruway.ws:9090', //You can use this demo server or replace it with your router's IP
realm: 'com.example.astro'
});
connection.onopen = function (session) {
//subscribe to a topic
function onevent(args) {
console.log("Someone published this to 'com.example.hello': ", args);
}
session.subscribe('com.example.hello', onevent).then(
function (subscription) {
console.log("subscription info", subscription);
},
function (error) {
console.log("subscription error", error);
}
);
};
connection.open();
我还为javascript方创建了一个plunker,为PHP方创建了一个runnable.