Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swoole WebSocket instance


May 14, 2021 Swoole


Table of contents


Introduction to Swoole WebSocket

swoole-1.7.9 adds built-in websocket server support to write an asynchronous non-blocking multi-process WebSocket server in a few lines of PHP code.

Common usage scenarios: When we're using php development, the worst thing to use natively is the socket class library, and in developing IM and timely communication projects, we now have a new option for back-end use php Swoole WebSocket and front-end html5 WebSocket;

A simple example:

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

OnRequest callback

swoole_websocket_server inherited from swoole_http_server

  • With the onRequest callback set, the websocket server can also act as a http server at the same time
  • The onRequest callback is not set, and the websocket server returns http 400 http request

Client

  • Browsers such as Chrome/Firefox/High Version IE/Safari have a WebSocket client in the JS language built in
  • In an asynchronous PHP program, you can Swoole\Http\Client as a WebSocket client
  • The synchronous WebSocket client provided by swoole/framework can be used in apache/php-fpm or other sync-blocked PHP programs
  • Non-WebSocket clients cannot communicate with WebSocket servers
You can even use a combination socket.io with development