在 Socket.io 中使用 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6398887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:14:36  来源:igfitidea点击:

Using PHP with Socket.io

phpsocket.io

提问by Yuvi

Is it possible to use Sockets.io on the client side and communicate with a PHP based application on the server? Does PHP even support such a 'long-lived connection' way of writing code?

是否可以在客户端使用 Sockets.io 并与服务器上基于 PHP 的应用程序进行通信?PHP 甚至支持这种“长期连接”的代码编写方式吗?

All the sample code I find for socket.io seems to be for node.js on the server side, so no help there.

我为 socket.io 找到的所有示例代码似乎都用于服务器端的 node.js,所以没有帮助。

回答by Florian Margaine

It may be a little late for this question to be answered, but here is what I found.

回答这个问题可能有点晚了,但这是我发现的。

I don't want to debate on the fact that nodes does that better than php or not, this is not the point.

我不想争论节点是否比 php 做得更好,这不是重点。

The solution is : I haven't found any implementation of socket.io for PHP.

解决方案是:我还没有找到任何用于 PHP 的 socket.io 实现。

But there are some ways to implement WebSockets. There is this jQuery pluginallowing you to use Websockets while gracefully degrading for non-supporting browsers. On the PHP side, there is this classwhich seems to be the most widely used for PHP WS servers.

但是有一些方法可以实现WebSockets。有这个 jQuery 插件允许您使用 Websockets 同时优雅地降级不支持的浏览器。在 PHP 方面,有这个类似乎是最广泛用于 PHP WS 服务器的类。

回答by kasper Taeymans

If you want to use socket.io together with php this may be your answer!

如果您想将 socket.io 与 php 一起使用,这可能就是您的答案!

project website:

项目网站:

elephant.io

大象网

they are also on github:

他们也在 github 上:

https://github.com/wisembly/elephant.io

https://github.com/wisembly/elephant.io

Elephant.io provides a socket.io client fully written in PHP that should be usable everywhere in your project.

Elephant.io 提供了一个完全用 PHP 编写的 socket.io 客户端,它应该可以在您的项目中的任何地方使用。

It is a light and easy to use library that aims to bring some real-time functionality to a PHP application through socket.io and websockets for actions that could not be done in full javascript.

它是一个轻量级且易于使用的库,旨在通过 socket.io 和 websockets 为 PHP 应用程序带来一些实时功能,用于无法在完整的 javascript 中完成的操作。

example from the project website (communicate with websocket server through php)

来自项目网站的示例(通过php与websocket服务器通信)

php server

php服务器

use ElephantIO\Client as Elephant;

$elephant = new Elephant('http://localhost:8000', 'socket.io', 1, false, true, true);

$elephant->init();
$elephant->send(
    ElephantIOClient::TYPE_EVENT,
    null,
    null,
    json_encode(array('name' => 'foo', 'args' => 'bar'))
);
$elephant->close();

echo 'tryin to send `bar` to the event `foo`';

socket io server

套接字io服务器

var io = require('socket.io').listen(8000);

io.sockets.on('connection', function (socket) {
  console.log('user connected!');

  socket.on('foo', function (data) {
    console.log('here we are in action event and data is: ' + data);
  });
});

回答by Alvin K.

UPDATE: Aug 2014The current socket.io v1.0site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

更新:2014 年 8 月当前的socket.io v1.0站点有一个 PHP 示例:- https://github.com/rase-/socket.io-php-emitter

回答by walkor

If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.

如果你真的想使用 PHP 作为 socket.io 的后端,这里是我发现的。两个socket.io php 服务器端替代。

https://github.com/walkor/phpsocket.io

https://github.com/walkor/phpsocket.io

https://github.com/RickySu/phpsocket.io

https://github.com/RickySu/phpsocket.io

Exmaple codes for the first repository like this.

像这样的第一个存储库的示例代码。

use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
  $socket->on('chat message', function($msg)use($io){
    $io->emit('chat message', $msg);
  });
});

回答by Chung Xa

For 'long-lived connection' you mentioned, you can use Ratchet for PHP. It's a library built based on Stream Socket functions that PHP has supported since PHP 5.

对于您提到的“长期连接”,您可以使用 Ratchet for PHP。它是一个基于 Stream Socket 函数构建的库,PHP 自 PHP 5 起就支持该函数。

For client side, you need to use WebSocket that HTML5 supported instead of Socket.io (since you know, socket.io only works with node.js).

对于客户端,您需要使用 HTML5 支持的 WebSocket 而不是 Socket.io(因为您知道,socket.io 仅适用于 node.js)。

In case you still want to use Socket.io, you can try this way: - find & get socket.io.js for client to use - work with Ratchet to simulate the way socket.io does on server

如果您仍然想使用 Socket.io,您可以尝试这种方式: - 查找并获取 socket.io.js 供客户端使用 - 与 Ratchet 一起模拟 socket.io 在服务器上的工作方式

Hope this helps!

希望这可以帮助!

回答by therealadrain

I know the struggle man! But I recently had it pretty much working with Workerman. If you have not stumbled upon this php framework then you better check this out!

我认识奋斗的人!但我最近与 Workerman 一起工作。如果您还没有偶然发现这个 php 框架,那么您最好检查一下!

Well, Workerman is an asynchronous event driven PHP framework for easily building fast, scalable network applications. (I just copied and pasted that from their website hahahah http://www.workerman.net/en/)

好吧,Workerman 是一个异步事件驱动的 PHP 框架,用于轻松构建快速、可扩展的网络应用程序。(我只是从他们的网站上复制并粘贴了哈哈哈http://www.workerman.net/en/

The easy way to explain this is that when it comes web socket programming all you really need to have is to have 2 files in your server or local server (wherever you are working at).

解释这一点的简单方法是,当涉及到 Web 套接字编程时,您真正需要的是在您的服务器或本地服务器(无论您在哪里工作)中有 2 个文件。

  1. server.php(source code which will respond to all the client's request)

  2. client.php/client.html(source code which will do the requesting stuffs)

  1. server.php(将响应所有客户端请求的源代码)

  2. client.php/client.html(将执行请求的源代码)

So basically, you right the code first on you server.phpand start the server. Normally, as I am using windows which adds more of the struggle, I run the server through this command --> php server.php start

所以基本上,您首先在server.php上修改代码并启动服务器。通常,由于我使用的窗口增加了更多的麻烦,我通过此命令运行服务器 --> php server.php start

Well if you are using xampp. Here's one way to do it. Go to wherever you want to put your files. In our case, we're going to the put the files in

好吧,如果您使用的是 xampp。这是一种方法。转到您想要放置文件的任何位置。在我们的例子中,我们将把文件放入

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/server.php

C:/xampp/htdocs/websocket/client.php or client.html

C:/xampp/htdocs/websocket/client.php 或 client.html

Assuming that you already have those files in your local server. Open your Git Bash or Command Line or Terminal or whichever you are using and download the php libraries here.

假设您的本地服务器中已经有这些文件。打开您的 Git Bash 或命令行或终端或您正在使用的任何一个,并在此处下载 php 库。

https://github.com/walkor/Workerman

https://github.com/walkor/Workerman

https://github.com/walkor/phpsocket.io

https://github.com/walkor/phpsocket.io

I usually download it via composer and just autoload those files in my php scripts.

我通常通过 composer 下载它,然后在我的 php 脚本中自动加载这些文件。

And also check this one. This is really important! You need this javascript libary in order for you client.phpor client.html to communicate with the server.phpwhen you run it.

还要检查这个。这真的很重要!您需要这个 javascript 库,以便您的client.php或 client.html在运行时与server.php进行通信。

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

https://github.com/walkor/phpsocket.io/tree/master/examples/chat/public/socket.io-client

I just copy and pasted that socket.io-client folder on the same level as my server.php and my client.php

我只是将 socket.io-client 文件夹复制并粘贴到与 server.php 和 client.php 相同的级别

Here is the server.phpsourcecode

这是server.php源代码

<?php
require __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
    $socket->on('send message', function($msg)use($io){
        $io->emit('new message', $msg);
    });
});

Worker::runAll();

And here is the client.phpor client.htmlsourcecode

这是client.phpclient.html源代码

<!DOCTYPE html>
<html>
    <head>
        <title>Chat</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">        
    </head>
    <body>
        <div id="chat-messages" style="overflow-y: scroll; height: 100px; "></div>        
        <input type="text" class="message">
    </body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>    
    <script src="socket.io-client/socket.io.js"></script>  
    <script>
            var socket = io.connect("ws://127.0.0.1:2021");

            $('.message').on('change', function(){
                socket.emit('send message', $(this).val());
                $(this).val('');
            });

            socket.on('new message', function(data){
                $('#chat-messages').append('<p>' + data +'</p>');
            });
    </script>
</html>

Once again, open your command line or git bash or terminal where you put your server.php file. So in our case, that is C:/xampp/htdocs/websocket/ and typed in php server.php startand press enter.

再次打开你的命令行或 git bash 或你放置 server.php 文件的终端。所以在我们的例子中,那就是 C:/xampp/htdocs/websocket/ 并输入php server.php start并按回车键。

Then go to you browser and type http://localhost/websocket/client.phpto visit your site. Then just type anything to that textbox and you will see a basic php websocket on the go!

然后转到您的浏览器并键入http://localhost/websocket/client.php以访问您的站点。然后只需在该文本框中输入任何内容,您就会在旅途中看到一个基本的 php websocket!

You just need to remember. In web socket programming, it just needs a server and a client. Run the server code first and the open the client code. And there you have it! Hope this helps!

你只需要记住。在 web socket 编程中,它只需要一个服务器和一个客户端。首先运行服务器代码,然后打开客户端代码。你有它!希望这可以帮助!

回答by PaulM

Erm, why would you want to? Leave PHP on the backend and NodeJS/Sockets to do its non-blocking thing.

嗯,你为什么要?将 PHP 留在后端,让 NodeJS/Sockets 做非阻塞的事情。

Here is something to get you started: http://groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc

这里有一些东西可以让你开始:http: //groups.google.com/group/socket_io/browse_thread/thread/74a76896d2b72ccc

Personally I have express running with an endpoint that is listening expressly for interaction from PHP.

就我个人而言,我已经与一个端点一起运行,该端点明确地监听来自 PHP 的交互。

For example, if I have sent a user an email, I want socket.io to display a real-time notification to the user.

例如,如果我向用户发送了一封电子邮件,我希望 socket.io 向用户显示实时通知。

Want interaction from socket.io to php, well you can just do something like this:

想要从 socket.io 到 php 的交互,你可以这样做:

var http = require('http'),
            host = WWW_HOST,
            clen = 'userid=' + userid,
            site = http.createClient(80, host),
            request = site.request("POST", "/modules/nodeim/includes/signonuser.inc.php",  
                {'host':host,'Content-Length':clen.length,'Content-Type':'application/x-www-form-urlencoded'});                     

request.write('userid=' + userid);      
request.end();  

Seriously, PHP is great for doing server side stuff and let it be with the connections it has no place in this domain now. Why do anything long-polling when you have websockets or flashsockets.

说真的,PHP 非常适合做服务器端的事情,让它与现在在这个域中没有位置的连接一起使用。当你有 websockets 或 flashsockets 时,为什么要进行长轮询。

回答by Sankalp Singha

How about this ? PHPSocketio?? It is a socket.io php server side alternative. The event loop is based on pecl event extension. Though haven't tried it myself till now.

这个怎么样 ?PHPSocketio?? 它是 socket.io php 服务器端的替代品。事件循环基于 pecl 事件扩展。虽然直到现在我自己还没有尝试过。

回答by mpen

I haven't tried it yet, but you should be able to do this with ReactPHPand this socket component. Looks just like Node, but in PHP.

我还没有尝试过,但是您应该可以使用ReactPHP和这个socket 组件来做到这一点。看起来就像 Node,但在 PHP 中。