Home > PHP Framework > Swoole > How to open ws with swoole

How to open ws with swoole

(*-*)浩
Release: 2019-12-16 10:22:43
Original
2704 people have browsed it

How to open ws with swoole

WebSocket (ws) is a new communication protocol added to html5. Currently, popular browsers support this protocol, such as Chrome, Safrie, Firefox, Opera , IE, etc., the earliest support for this protocol should be chrome, which has been supported since chrome12. As the protocol draft continues to change, each browser's implementation of the protocol is also constantly updated. (Recommended learning: swoole video tutorial)

swoole 1.7.9 adds built-in WebSocket server support, and you can write an asynchronous non-blocking multi-process with a few lines of PHP code WebSocket server.

$server = new Swoole\WebSocket\Server("0.0.0.0", 9501);
$server->on('open', function (Swoole\WebSocket\Server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});
$server->on('message', function (Swoole\WebSocket\Server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "this is server");
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();
Copy after login

In addition to receiving the callback functions of the Swoole\Server and Swoole\Http\Server base classes, the WebSocket server adds 3 additional callback function settings. Among them:

onMessage callback function is required

onOpen and onHandShake callback functions are optional

WebSocket\Server is a subclass of Server, so All methods of Server can be called.

It should be noted that the WebSocket server should use the WebSocket\Server::push method to send data to the client. This method will package the WebSocket protocol. The Server::send method is the original TCP sending interface.

The WebSocket\Server::disconnect method can actively close a WebSocket connection from the server and specify the status code (according to the WebSocket protocol, the usable status code is a decimal integer, and the value can be 1000 or 4000 -4999) and the reason for closing (a string encoded in UTF-8 and with a length of no more than 125 bytes).

If not specified, the status code is 1000 and the shutdown reason is empty

The above is the detailed content of How to open ws with swoole. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template