PHP中的永久本地域套接字 [英] Persistent local domain socket in php

查看:216
本文介绍了PHP中的永久本地域套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个问题找到的答案(例如此处此处 ,并且这里)都涉及pfsockopen(),似乎适用于非本地套接字连接。但是,到目前为止,我编写的代码使用php通过本地连接访问C ++服务器。我希望这种连接是持久的(顺便说一下,这样我就可以将其用于Comet)。这是我的非永久版本:

The answers I've found to this question (such as here, here, and here) all involve pfsockopen(), which seems geared to non-local socket connections. However, the code I've written so far uses php to access a C++ server through a local connection. I want this connection to be persistent (so that I can use it for Comet, incidentally). Here's my non-persistent version:

<?php
session_start();

...

if (($sock = socket_create(AF_UNIX, SOCK_STREAM,0)) === false)
{
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
        exit();
}
$sess_id = $_SESSION['sess_id'];
$sock_str = '/tmp/sockdir/' . $sess_id; //The socket is named after the php session, not important
if (socket_connect($sock, $sock_str) === false)
{
        echo "socket_connect() to " . $sock_str . " failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
        socket_close($sock);
        exit();
}

$msg = $_GET['message'];

// ... do things with $msg

socket_close($sock);
?>

现在我不能简单地将'$ sock'保存为$ _SESSION变量并分别访问每个变量我发现了这个脚本的调用时间。我有什么技巧可以将其变成持久连接?<​​/ p>

Now I can't simply save '$sock' as a $_SESSION variable and simply access it each time this script is called, I've found. Any tips on what I can do to turn this into a persistent connection?

推荐答案

正如您提供的链接所指出的那样,php是不是持久性语言,也无法跨会话保持持久性(即页面加载)。您可以通过运行第二个php脚本作为守护程序来创建中间立场,并使您的主脚本(即用户点击的脚本)连接到该脚本(是的-通过套接字...)并从中获取数据。

As the links you provided point out, php is not a persistent language and there is no way to have persistence across sessions (i.e. page loads). You can create a middle ground though by running a second php script as a daemon, and have your main script (i.e. the one the user hits) connect to that (yes - over a socket...) and get data from it.

如果要这样做,并且希望避免Web套接字的麻烦,请尝试使用新的HTML5 EventStream API ,因为它可以为您提供两全其美的功能:像基础设施这样的Commet,无需冗长的轮询或专门的Web套接字服务器。

If you were to do that, and want to avoid the hassel of Web Sockets, try the new HTML5 EventStream API, as it gives you the best of both worlds: A commet like infrastructure without the hackyness of long-polling or the need for a dedicated Web Sockets server.

这篇关于PHP中的永久本地域套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆