Write the Code. Change the World.

11月 11

只要 websocket 服务。最简单化的 websocket 服务。不需要其他基于 swoole 的其他框架应用。仅仅 swoole 扩展 + php + nginx 完成 websocket 的服务。就是想最简单简洁的实现。

就像官方的实例一样 https://wiki.swoole.com/#/start/start_ws_server,就这么些代码。

$ws = new Swoole\WebSocket\Server('0.0.0.0', 9502);

//监听WebSocket连接打开事件
$ws->on('Open', function ($ws, $request) {
    $ws->push($request->fd, "hello, welcome\n");
});

//监听WebSocket消息事件
$ws->on('Message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    $ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('Close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();

我们不喜欢用 ip 来连接,我们用域名。我们不喜欢用 http,我们用 https。我们不喜欢加端口号,我们用代理。这里我们用 nginx 来搞定。比如吧,我们自己的域名是: xx.com, nginx 就可以像下边这样配置:

map $http_upgrade $connection_upgrade {  
    default upgrade;  
    '' close;  
}

server 
{    
    listen 443 ssl http2; 
    server_name xx.com;

    ssl_certificate         /usr/local/server/nginx/conf/ssl/xx.com.pem;
    ssl_certificate_key     /usr/local/server/nginx/conf/ssl/xx.com.key;

    charset utf-8;
    index index.php index.html index.htm;
    root /www/xx/xx.com/public;

    location /wss {
        # 代理到上边的自定义的地址
        proxy_pass http://127.0.0.1:9502;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location / {
        try_files $uri $uri/  /index.php?$query_string; 
    }

    location ~ \.php($|/) {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param HTTPS $https if_not_empty;
        fastcgi_split_path_info ^(.+\.php)(.*)$;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

服务端的配置构建的重要部分就算好了。需要注意的是,创建 websocket 的时候,一定不要带上 ssl 相关的参数和证书。这样你 nginx 这边请求代理过去是 http 请求,就会出错。

websocket 这里没有心跳功能,可以手动模拟创建一个,去实现类似的业务。

还有,在服务端可以使用 swoole 自己的存储结构。 https://wiki.swoole.com/#/memory/table

旧的文章

https://blog.vini123.com/405

https://blog.vini123.com/482

https://blog.vini123.com/294