Hello!
I am trying to figure out how one can incorporate a redis client into a websocket server. The usage scenario is as follows:
(a) The WebSocket Server establishes a client connection to a Redis server and executes a SUBSCRIBE command, effectively waiting for messages flowing from the upstream
(b) The WebSocket Server accepts WS connections and once registered, it might forward them messages received from the Redis server upstream
I am not sure if this is doable with the standard out of the box API or one has to employ the event loop API.
What did you do? If possible, provide a recipe for reproducing the error.
N/A
What did you expect to see?
N/A
What did you see instead?
N/A
What version of Swoole are you using (php --ri swoole)?
2.0.8
What is your machine environment used (including version of kernel & php & gcc) ?
Linux Kernel 4.9, PHP v7.0.19, gcc v6.30
If you are using ssl, what is your openssl version?
1.1.0f
The php-redis extension is an blocking IO client. It will cause event loop to block. You should use swoole_redis.
$server = new swoole_websocket_server("0.0.0.0", 9501);
$server->on('workerStart', function ($server, $workerId) {
$client = new swoole_redis;
$client->on('message', function (swoole_redis $client, $result) use ($server) {
if ($result[0] == 'message') {
foreach($server->connections as $fd) {
$server->push($fd, $result[1]);
}
}
});
$client->connect('127.0.0.1', 6379, function (swoole_redis $client, $result) {
$client->subscribe('msg_0');
});
});
$server->on('open', function ($server, $request) {
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
$server->push($frame->fd, "hello");
});
$server->on('close', function ($serv, $fd) {
});
$server->start();
Most helpful comment
The
php-redisextension is an blocking IO client. It will cause event loop to block. You should useswoole_redis.example