ratchet教程_如何使用Ratchet快速构建聊天应用程序

ratchet教程In this tutorial, we’ll be taking a look at Ratchet, a PHP library for working with WebSockets. Let’s start by defining what WebSockets are. MDN says: 在本教程中,我们将看一下Ratchet (一个用于处理WebSocketsPH...
摘要由CSDN通过智能技术生成

ratchet教程

In this tutorial, we’ll be taking a look at Ratchet, a PHP library for working with WebSockets. Let’s start by defining what WebSockets are. MDN says:

在本教程中,我们将看一下Ratchet (一个用于处理WebSocketsPHP库)。 让我们开始定义什么是WebSockets。 MDN说:

WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

WebSockets是一项先进的技术,可以打开用户浏览器和服务器之间的交互式通信会话。 使用此API,您可以将消息发送到服务器并接收事件驱动的响应,而不必轮询服务器以获取答复。

Connected computers image

WebSockets allow us to write applications that can pass data from the browser to the server and vice-versa in real-time.

WebSockets允许我们编写应用程序,这些应用程序可以实时将数据从浏览器传递到服务器,反之亦然。

建立 (Setup)

First, let’s install Ratchet using Composer:

首先,让我们使用Composer安装Ratchet:

composer require cboden/ratchet

构建应用 (Building the App)

Now we’re ready to build the app. Create a Chat.php file under the class/ChatApp directory. This would be a class under the ChatApp namespace, and it would use use Ratchet’s MessageComponentInterface and ConnectionInterface. The MessageComponentInterface is used as the basic building block for Ratchet applications, while the ConnectionInterface represents the connection to the application.

现在我们准备构建该应用程序。 在class/ChatApp目录下创建一个Chat.php文件。 这将是ChatApp命名空间下的类,并且将使用Ratchet的MessageComponentInterfaceConnectionInterfaceMessageComponentInterface用作Ratchet应用程序的基本构建块,而ConnectionInterface表示与应用程序的连接。

<?php
namespace ChatApp;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

Have the class implement the MessageComponentInterface. This contains the blueprint for the methods that we need to implement such as onOpen, onClose and onMessage.

让类实现MessageComponentInterface 。 这包含我们需要实现的方法的蓝图,例如onOpenonCloseonMessage

class Chat implements MessageComponentInterface {

}

Inside the class, we declare a variable called $clients. This is where we will store a list of currently connected clients in our chat app later on. From the constructor, you will see that we’re using SplObjectStorage. This provides a way for us to store objects. In this case, the object that we need to store is the connection object for each client.

在类内部,我们声明一个名为$clients的变量。 稍后,我们将在这里将当前连接的客户端列表存储在聊天应用程序中。 从构造函数中,您将看到我们正在使用SplObjectStorage 。 这为我们提供了一种存储对象的方法。 在这种情况下,我们需要存储的对象是每个客户端的连接对象。

protected $clients;

public function __construct() {
    $this->clients = new \SplObjectStorage;
}

Next, we implement the onOpen method. This method is called every time a new connection is opened in the browser. What this does is store the new connection object using the attach method. We also output that someone has connected as a means of testing if the onOpen method is working correctly.

接下来,我们实现onOpen方法。 每次在浏览器中打开新连接时,都会调用此方法。 这样做是使用attach方法存储新的连接对象。 我们还输出有人已连接,以测试onOpen方法是否正常工作。

public function onOpen(ConnectionInterface $conn) {
    //store the new connection
    $this->clients->attach($conn);

    echo "someone connected\n";
}

Next is the onMessage method. This method is called every time a message is sent by a specific client in the browser. The connection object of the client who sent the message, as well as the actual message, are passed along as an argument every time this method is called. All we do is loop through all the currently connected clients and send the message to them. In the code below, we’re checking if the client in the current iteration of the loop is the one who sent the message. We don’t want to send the same message to the person who sent it.

接下来是onMessage方法。 每当浏览器中的特定客户端发送消息时,都会调用此方法。 每次调用此方法时,发送消息的客户端的连接对象以及实际消息都会作为参数传递。 我们要做的就是遍历所有当前连接的客户端并将消息发送给它们。 在下面的代码中,我们正在检查循环的当前迭代中的客户端是否是发送消息的客户端。 我们不想

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Ratchet是一个PHP实现的WebSocket库,用于在Web应用程序中实现实时双向通信。下面是一个简单的示例,演示如何使用Ratchet创建WebSocket服务器: 1. 首先,需要安装Ratchet。可以使用Composer来安装Ratchet: ``` composer require cboden/ratchet ``` 2. 创建一个WebSocket服务器 ```php use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; require 'vendor/autoload.php'; class MyWebSocketServer implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); echo "New connection! ({$conn->resourceId})\n"; } public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->clients as $client) { if ($from !== $client) { $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); echo "Connection {$conn->resourceId} has disconnected\n"; } public function onError(ConnectionInterface $conn, \Exception $e) { echo "An error has occurred: {$e->getMessage()}\n"; $conn->close(); } } $server = new \Ratchet\App('localhost', 8080); $server->route('/', new MyWebSocketServer); $server->run(); ``` 在上面的示例中,我们创建了一个MyWebSocketServer类,它实现了Ratchet的MessageComponentInterface接口。在构造函数中,我们创建了一个SplObjectStorage对象,用于存储客户端连接。 在onOpen()方法中,我们将新的连接添加到SplObjectStorage中,并输出一条消息。 在onMessage()方法中,我们遍历所有客户端连接,并向除发送方外的所有客户端发送消息。 在onClose()方法中,我们从SplObjectStorage中删除连接,并输出一条消息。 在onError()方法中,我们输出错误消息,并关闭连接。 在最后几行代码中,我们创建了一个WebSocket服务器,并将MyWebSocketServer类与根路径/关联。然后调用run()方法启动服务器。 3. 运行WebSocket服务器 要运行WebSocket服务器,请在终端中导航到包含上面代码的文件夹,然后运行以下命令: ``` php server.php ``` 这将启动WebSocket服务器并开始监听来自客户端的连接。 4. 在客户端上测试WebSocket服务器 要测试WebSocket服务器,请打开一个现代Web浏览器(如Chrome或Firefox),并在地址栏中输入以下URL: ``` ws://localhost:8080 ``` 这将尝试建立到WebSocket服务器的连接。如果连接成功,您应该看到控制台输出“New connection!”消息。 现在,您可以使用JavaScript编写WebSocket客户端,以便从服务器接收和发送消息。例如,以下是一个简单的JavaScript WebSocket客户端示例: ```javascript var conn = new WebSocket('ws://localhost:8080'); conn.onopen = function(e) { console.log("Connection established!"); conn.send("Hello Server!"); }; conn.onmessage = function(e) { console.log("Received message: " + e.data); }; ``` 在上面的示例中,我们创建了一个WebSocket连接,并在连接打开时发送一条消息。在收到来自服务器的消息时,我们将消息输出到控制台。 这就是Ratchet的基本用法。使用Ratchet,您可以轻松地在Web应用程序中实现实时双向通信。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值