Chức năng ổ cắm php

A multicast server can be written badly as follows:

$bc_string = "Hello World!";
$sock = socket_create[AF_INET, SOCK_DGRAM, 0];
$opt_ret = socket_set_option[$sock, 1, 6, TRUE];
$send_ret = socket_sendto[$sock, $bc_string, strlen[$bc_string], 0, '230.0.0.1', 4446];

Checking the return types is needed, but this does allow for you to multicast from php code.

Trước khi nghĩ đến chủ đề này mình có search trên viblo với từ khóa websocket viblo xem đã có ai viết về mục này chưa và kết quả là đã có rất nhiều bài viết về mục này nhưng đa số là lý thuyết. Để hiện thực hóa những lý thuyết đã được đọc thì trong phạm vi bài viết này mình xin giới thiệu về cách xây dựng 1 ứng dụng chat cơ bản sử dụng thư viện Ratchet - WebSockets for PHP. Lý thuyết cơ bản về WebSocket các bạn có thể tham khảo tại đây

2. Bắt đầu thử một bài cơ bản với PHP WebSocket

Là người thích cái đẹp và vẽ vời mình luôn mong muốn những sản phẩm của bản thân cho dù đơn giản nhất thì trước hết vẫn phải đẹp mắt. . v Vì thế lại một lần nữa nhờ Google với từ khóa chat box template và sau 2 phút mình đã chọn ra được cái mặt tiền cho cái ứng dụng đơn giản này, nó ở đây. Load về giải nén ra ta có mục chat-box. Tạm thời chưa cần động đến nó, tiếp theo ta sẽ thực hiện theo cái hello-world của Ratchet để xem nó là cái gì đã

Vào luôn hộp trò chuyện thư mục, nhập lệnh composer require cboden/ratchet để thêm thư viện vào dự án. Sau đó ta thêm 1 class [src/ChatWebSocket/Chat. php] with the content as after

namespace ChatWebSocket;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;

    public function __construct[] {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen[ConnectionInterface $conn] {
        // Store the new connection to send messages to later
        $this->clients->attach[$conn];

        echo "New connection! [{$conn->resourceId}]\n";
    }

    public function onMessage[ConnectionInterface $from, $msg] {
        $numRecv = count[$this->clients] - 1;
        echo sprintf['Connection %d sending message "%s" to %d other connections' . "\n"
            , $from->resourceId, $msg, $numRecv];

        foreach [$this->clients as $client] {
            if [$from !== $client] {
                // The sender is not the receiver, send to each client connected
                $client->send[$msg];
            }
        }
    }

    public function onClose[ConnectionInterface $conn] {
        // The connection is closed, remove it, as we can no longer send it messages
        $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[];
    }
}

Nhìn qua lớp nội dung ta cũng có thể hiểu được ý nghĩa của từng phương thức qua comment bên cạnh, mép lật lại thì lớp này triển khai các sự kiện của WebSocket đó là

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use ChatWebSocket\Chat;

require dirname[__DIR__] . '/vendor/autoload.php';

$server = IoServer::factory[
    new HttpServer[
        new WsServer[
            new Chat[]
        ]
    ],
    8080
];
$server->run[];
0. Continue ta will create a shell script to open 1 connect socket, create file script chat_server. php in the bin directory/ with the content as after

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use ChatWebSocket\Chat;

require dirname[__DIR__] . '/vendor/autoload.php';

$server = IoServer::factory[
    new HttpServer[
        new WsServer[
            new Chat[]
        ]
    ],
    8080
];
$server->run[];

To run the script on ta run command

php bin/chat_server.php

Chạy xong câu lệnh, ta đã mở được 1 kết nối websocket có thể lắng nghe mọi yêu cầu trên cổng 8080. Bây giờ ở phía client ta sẽ thử test bằng cách như sau, mở 2 trình duyệt [Ví dụ Chrome và Firefox] lên nhấn F12 mở console ra và dán dòng lệnh này vào để khởi động connect socket đến server ta đã chạy script ở trên

var conn = new WebSocket['ws://localhost:8080'];
conn.onopen = function[e] {
    console.log["Connection established!"];
};

conn.onmessage = function[e] {
    console.log[e.data];
};

Ở Chrome ta gõ vào dòng lệnh

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use ChatWebSocket\Chat;

require dirname[__DIR__] . '/vendor/autoload.php';

$server = IoServer::factory[
    new HttpServer[
        new WsServer[
            new Chat[]
        ]
    ],
    8080
];
$server->run[];
1 thì ở bên Firefox thông báo
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use ChatWebSocket\Chat;

require dirname[__DIR__] . '/vendor/autoload.php';

$server = IoServer::factory[
    new HttpServer[
        new WsServer[
            new Chat[]
        ]
    ],
    8080
];
$server->run[];
2 sẽ ngay lập tức ghi ra bảng điều khiển. Bằng cách test như vậy thì ta cũng có thể hiểu được cơ bản về cơ chế hoạt động của nó. Giờ thì đến giai đoạn gặt lúa và đi thôi. Thêm vài đường cơ bản vào file mặt tiền mà ta đã về ngay đâu tiên. Và cuối cùng ta có kết quả như sau

3. Kết luận

Bằng ứng dụng demo đơn giản trên ta có thể hiểu rõ hơn về Websocket. Trong phần tiếp theo mình sẽ tiếp tục vẽ vời thêm với một vài ý tưởng trong đầu để nghịch thêm về bánh cóc. Cảm ơn các bạn đã theo dõi bài viết. Còn tiếp

Chủ Đề