- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 symfony 2 开发了一个网站。直到现在它还没有使用ajax。当您发布新评论时,页面已刷新。
我添加了一个 ajax 层,因此无需刷新即可提交表单。
每次我发布新帖子时,我都希望允许所有在线用户在他们的时间线中看到这篇帖子。
这就是我现在所做的:
我创建了一个事件 NewPostAdded 和一个订阅者渲染到 html 帖子(希望我将它发送给客户端并且客户端将 $('.timeline').prepend(post) )
我正在寻找一种方法来实现将启动 websocket 服务器的 symfony2 命令。我的订户将能够将帖子+数据(它是公开的吗?否则允许查看它的用户 ID 列表)推送到此服务器。然后,该服务器将有一个在线用户列表,如果该帖子是公开的,它将推送给其他所有人,并将其推送给正确的在线用户。
我在使用 symfony 2.1 + redis + nodejs + socket.io 之前已经这样做了,但它显然无法维护,而且由于这个网站不是针对大量观众的,所以我想保持简单。
这是我的第二个问题:
是否有一个 bundle 使思考变得简单,提供了一种简单的方式来编写带有收入事件监听器(从 symfony 接收帖子)和事件发送器(向用户发送帖子)的服务器,添加事件监听器客户端(准备好使用 Assets 添加以能够对客户端进行编码)对服务器消息使用react?
有没有办法在客户端使用除用户 ID 之外的其他东西来“验证”websocket 服务器上的用户,以避免用户更改客户端代码中的 ID 以接收他们不应该查看的帖子?
最佳答案
是的,你可以使用 php web socket Ratchet "http://socketo.me/ ",你可以将它用作 composer 包 https://packagist.org/packages/cboden/ratchet
您应该创建一个服务应用程序,然后您应该创建一个将运行套接字应用程序的控制台命令。
您应该生成一个 secret token ,例如 userId 的 md5 散列 + 一些将用于检查套接字连接是否可信的 secret key ,而不是 userId。
更新:
Composer .json
...
"cboden/ratchet": "0.3.*",
...
然后你应该创建一个新的包,假设是“WebSocketBundle”
namespace MyApp\WebSocketBundle\WebSocket;
use Ratchet\ConnectionInterface;
use Ratchet\MessageComponentInterface;
class WebSocketApplication implements MessageComponentInterface
{
protected $container;
protected $clients;
protected $redis;
public function __construct($container)
{
$this->clients = [];
$this->container = $container;
$this->redis = $container->get('snc_redis.something'); // your redis service
}
public function onMessage(ConnectionInterface $from, $msg)
{
$messageData = $this->decodeJSONAndCheckMessage($from, $msg);
// here you must pass a token in messageData and implement own function to check is the token valid
$loginResult = $this->userLogin($from, $messageData);
if ($loginResult instanceof Success) { // my custom success class message
$this->handleMessage($from, $messageData);
} else {
$this->onError($from, new \Exception('Cannot login a user.'));
}
}
// some strategy wrapper
private function handleMessage($from, $messageData)
{
$message = $messageData->message;
if (method_exists($this, $message)) {
try {
$this->$message($from, $messageData);
} catch (Exception $ex) {
$this->onError($from, $ex);
}
} else {
$this->onError($from, new \Exception(sprintf('Unknown method "%s"', $message)));
}
}
// you can use here post new message action
private function eventStartSomething($from, $messageData)
{
if (!$messageData->somethingId) {
$this->onError($from, new \Exception('Bad parameters'));
return;
}
$scope = [];
$scope['clients'][$from->resourceId] = null;
// I need socket for something only limited amount of time, you can implement here own logic
$this->redis->setex($messageData->somethingId, 600, serialize($scope));
$this->clients[$from->resourceId]['scope'] = $messageData->eventId;
$this->logMessage($from, 'started new something with Id: ' . $messageData->somethingId);
$from->send($this->getResultOKMessage());
}
private function eventGetSomething($from, $messageData)
{
$scopeKey = $this->redis->get($messageData->somethingId);
if (!$scopeKey) {
$this->onError($from, new \Exception('Bad or expired something ' . $messageData->somethingId));
return;
}
if (!$this->checkForClientInScope($from->resourceId, $messageData->eventId)) {
if ($this->assignClientToScope($from->resourceId, $messageData->eventId)) {
$this->sendMessageToScope($from, $messageData->eventId, $this->getScopeWatchMessage($from, $messageData->eventId));
$from->send($this->getScopeWatchMessage($from, $messageData->eventId));
}
}
}
private function assignClientToScope($clienResourseId, $scopeId)
{
$result = false;
$scopeKey = $this->redis->get($scopeId);
if (!$scopeKey) {
return $result;
}
$scope = unserialize($scopeKey);
if (!array_key_exists($clienResourseId, $scope['clients'])) {
// I need socket for something only limited amount of time, you can implement here own logic
$this->redis->setex($scopeId, 600, serialize($scope));
if (array_key_exists($clienResourseId, $this->clients)) {
$this->clients[$clienResourseId]['scope'] = $scopeId;
}
$result = true;
}
return $result;
}
private function sendMessageToScope($from, $scopeId, $message)
{
$scopeKey = $this->redis->get($scopeId);
if (!$scopeKey) {
$this->onError($from, new \Exception('Bad or expired event ' . $scopeId . ' for sending message'));
return;
}
$scope = unserialize($scopeKey);
foreach ($scope['clients'] as $clientResourceId => $remoteAddress) {
if (array_key_exists($clientResourceId, $this->clients) &&
$this->clients[$clientResourceId]['connection'] != $from) {
$this->clients[$clientResourceId]['connection']->send($message);
}
}
}
public function onClose(ConnectionInterface $conn)
{
if (isset($this->clients[$conn->resourceId]['scope'])) {
$scopeId = $this->clients[$conn->resourceId]['scope'];
$this->removeClientFromScope($conn->resourceId);
$this->sendMessageToScope($conn, $scopeId, $this->getScopeWatchMessage($conn, $scopeId));
}
unset($this->clients[$conn->resourceId]);
$this->logMessage($conn, 'Connection closed.');
}
public function onError(ConnectionInterface $conn, \Exception $e)
{
echo date("Y-m-d H:i:s") . ":" . "WebSocket error::" . $e->getMessage() . " resourceId:" . $conn->resourceId . ". remoteAddress:" . $conn->remoteAddress . "\n";
$conn->send($this->getErrorMessage($e->getMessage()));
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients[$conn->resourceId]['connection'] = $conn;
$this->logMessage($conn, 'New connection.');
}
}
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Snc\RedisBundle\Session\Storage\Handler\RedisSessionHandler;
use Ratchet\Session\SessionProvider;
use MyApp\WebSocketBundle\WebSocket\WebSocketApplication;
class ListenCommand extends ContainerAwareCommand
{
protected function configure()
{
$this->setName('myapp:websocket:listen')
->setDescription('Listen for websocket requests ')
->addOption('port', 'p', InputOption::VALUE_REQUIRED, 'The port to listen on', 8000)
->addOption('interface', 'i', InputOption::VALUE_REQUIRED, 'The interface to listen on', '0.0.0.0');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$redis = $this->getContainer()->get('snc_redis.default');
$application = new WebSocketApplication($this->getContainer());
$server = IoServer::factory(
new HttpServer(
new WsServer(
new SessionProvider(
$application,
new RedisSessionHandler($redis)
)
)
),
$input->getOption('port'),
$input->getOption('interface')
);
echo "Listening on: ".$input->getOption('interface').":".$input->getOption('port')."\n";
$server->run();
}
}
关于javascript - 有没有一种干净的方法可以使用 symfony 2.6 设置 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30290034/
假设浏览器被强制终止,并且没有关闭消息发送到 Tornado 服务器。 Tornado 怎么知道(或者它甚至知道?)这个连接已经在客户端终止了?翻看Tornado websocket code这对我来
我目前正在开发一款使用 WebSockets 的基于浏览器的多人游戏。我的首要任务是低延迟以及与各种平台和网络设置的兼容性。 但是我正在做密码验证。我还有聊天功能,我认为玩家的隐私很重要。因此,我认为
我必须设计一个解决方案,允许通过远程托管的网络应用程序读取本地传感器生成的实时数据。 设计仍在进行中:传感器的数据可以由安装在客户端计算机上的 Windows 应用程序/服务处理,或者由位于客户端计算
WebSocket的端口是什么? WebSocket 使用什么协议(protocol)? 当防火墙阻止除 80 和 443 端口之外的所有端口时,WebSocket 是否工作? 最佳答案 What i
有一个 fantastic answer其中详细介绍了 REST apis 的工作原理。 websockets 如何以类似的细节工作? 最佳答案 Websocket 创建并代表了服务器和客户端之间双向
请原谅我的无知,因为我在负载均衡器和 websockets 方面的经验有限。我试图了解客户端如何通过 websockets 连接到位于负载均衡器后面的服务器集群。 我对负载均衡器的理解是它们就像反向代
我正在尝试使用 websocket 发送音频消息,我应该将音频流更改为什么类型的消息,以便我可以使用套接字发送? 如果我直接使用 websocket.send(audio),我会得到一个错误“DOME
我对 WebSockets 的前景感到非常兴奋。由于我在过去构建了一些基于桌面套接字的游戏和 Web 游戏,因此我热衷于将这两种方法结合起来构建基于 Web 的多人游戏,而无需长时间轮询。 自从 Fi
我读过很多关于实时推送通知的文章。并且简历是 websocket 通常是首选技术,只要您不关心 100% 的浏览器兼容性。然而,one article指出 Long polling - potenti
我很难找到文档或教程,以便通过网络套接字发送文件。 这是我的JS: ['dragleave', 'drop'].forEach(event_name => document.addEventListe
我正在使用 Dart 的 WebSocket 类(dart:io 和 dart:html 版本)连接到 Dart WebSocket 服务器。当我让客户端使用自定义关闭代码和原因关闭 Web 套接字连
谷歌浏览器框架是否支持 websocket? 最佳答案 答案是肯定的,Chrome Frame supports websockets .我不确定,但这也可能取决于您安装的 Chrome 版本。我有
是否可以在同一应用程序(同一端口)中托管一个普通 Bottle 应用程序和一个 WebSocket 应用程序(例如: https://github.com/defnull/bottle/blob/ma
我有一个支持网络套接字的服务器。浏览器连接到我的网站,每个浏览器都会打开一个到 www.mydomain.example 的 Web 套接字。这样,我的社交网络应用程序就可以向客户端推送消息。 传统上
我是 Websockets 新手。在阅读有关 websockets 的内容时,我无法找到一些疑问的答案。我希望有人能澄清一下。 websocket 是否仅将数据广播到所有连接的客户端而不是发送到特定客
客户端可以通过 websockets 连接到服务器多长时间?是否有时间限制,它们是否有可能连在一起多年? 最佳答案 理论上,WebSocket 连接可以永远持续下去。假设端点保持正常运行,长期存在的
我正在尝试使用 websockets 制作自己的聊天客户端,并认为我会从 Tomcat 7 websocket chat example code. 开始。 .我已经成功编译并部署了ChatAnnot
我有一个使用 AdSense 的应用程序,据我所知,由于 AdSense 政策,不允许进行轮询。我想知道如果我使用 WebSockets 并且服务器在创建新数据时向客户端发送新数据并且在客户端上显示新
在 servlet 世界中,我会使用 cookie 和 HttpSession 之类的东西来识别谁在访问我的 Restful 服务以将请求路由到正确的数据。将 Sec-WebSocket-Key 用作
我必须使用 websocket 实现一个聊天应用程序,用户将通过群组聊天,可以有数千个群组,并且一个用户可以在多个群组中。我正在考虑两种解决方案: [1] 对于每个群聊,我创建一个 websocket
我是一名优秀的程序员,十分优秀!