sse / libsse
该软件包最新版本(dev-master)没有可用的许可信息。
dev-master
2015-01-20 10:45 UTC
Requires
- php: >=5.4.0
This package is auto-updated.
Last update: 2024-09-13 21:08:04 UTC
README
一个易于使用的、面向对象的 Server-Sent Events 库
更新
- 添加新功能:现在通过 SSEData 可以实现跨脚本通信。
- 添加示例,演示新功能:用 libSSE 在不到 100 行 PHP 代码内构建聊天室!
- 更简洁的代码
- 添加文档。 查看这里
- 改进输出缓冲的代码
开发
这是一个活跃的项目。如果你想要帮助我,请提出建议,跟踪问题或寻找错误。如果你喜欢它,请考虑给它加星,让更多的人知道。
快速使用
服务器端(PHP)
<?php
require_once('./src/libsse.php');//include the library
//create the event handler
class YourEventHandler extends SSEEvent {
public function update(){
//Here's the place to send data
return 'Hello, world!';
}
public function check(){
//Here's the place to check when the data needs update
return true;
}
}
$sse = new SSE();//create a libSSE instance
$sse->addEventListener('event_name',new YourEventHandler());//register your event handler
$sse->start();//start the event loop
?>
客户端(javascript)
var sse = new EventSource('path/to/your/sse/script.php');
sse.addEventListener('event_name',function(e){
var data = e.data;
//handle your data here
},false);
设置
创建 libSSE 实例后,有一些设置供你控制行为。以下是由库提供的设置。
<?php
require_once('./src/libsse.php');
$sse = new SSE();
$sse->exec_limit = 10; //the execution time of the loop in seconds. Default: 600. Set to 0 to allow the script to run as long as possible.
$sse->sleep_time = 1; //The time to sleep after the data has been sent in seconds. Default: 0.5.
$sse->client_reconnect = 10; //the time for the client to reconnect after the connection has lost in seconds. Default: 1.
$sse->use_chunked_encodung = true; //Use chunked encoding. Some server may get problems with this and it defaults to false
$sse->keep_alive_time = 600; //The interval of sending a signal to keep the connection alive. Default: 300 seconds.
$sse->allow_cors = true; //Allow cross-domain access? Default: false. If you want others to access this must set to true.
?>
兼容性
由于服务器发送事件是一个新标准,并且还在不断发展中,只有某些浏览器支持它。然而,服务器发送事件的 polyfill 是可用的。另外,在共享主机上,它可能会禁用 PHP 的 set_time_limit
函数,库可能无法按预期工作。库中提供了一些设置可以修复它。