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();
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!