下面介绍基于workerman实现的PHP版本的socket.IO——phpsocket.io的安装。
详细文档请见https://github.com/walkor/phpsocket.io/tree/master/docs/zh
1、添加用户及用户目录,并指定默认shell
useradd -d /home/xushanxiang -m xushanxiang -s /bin/bash
2、设定新用户的密码
passwd xushanxiang
3、创建一个目录,并给予xushanxiang账号权限
mkdir im01
chown xushanxiang:xushanxiang im01/
4、切换用户,并改变目录权限
su xushanxiang
chmod -R 777 im01
5、进入im01目录,并局部安装Composer
cd im01/
curl -sS https://getcomposer.org/installer | php
php composer.phar
6、在当前目录中创建一个基本的composer.json文件
php composer.phar init
cat composer.json
得到:
{
"name": "xushanxiang/im01",
"require": {}
}
7、使用 国内Composer 镜像加速
php composer.phar config repo.packagist composer https://packagist.phpcomposer.com
cat composer.json
得到:
{
"name": "xushanxiang/im01",
"require": {},
"repositories": {
"packagist": {
"type": "composer",
"url": "https://packagist.phpcomposer.com"
}
}
}
8、安装phpsocket.io
php composer.phar require workerman/phpsocket.io
tree -L 3
得到:
|-- composer.json
|-- composer.lock
|-- composer.phar-- vendor
|-- autoload.php
|-- composer
-- workerman
# composer.json
{
"name": "xushanxiang/im01",
"require": {
"workerman/phpsocket.io": "^1.1"
},
"repositories": {
"packagist": {
"type": "composer",
"url": "https://packagist.phpcomposer.com"
}
}
}
9、创建一个SocketIO服务端,回到项目根目录,新建server.php,内容如下:
<?php
require_once DIR . '/vendor/autoload.php';
use Workerman\Worker;
use PHPSocketIO\SocketIO;
// 创建socket.io服务端,监听3120端口
// 记得在防火墙开启此端口,例如:
// sudou fw allow 3120
// 查看:sudo ufw status
// 删除:sudo ufw delete allow 3120
$io = new SocketIO(3120);
// 当有客户端连接时打印一行文字
$io->on('connection', function($socket)use($io){
echo "new connection coming\n";
});
Worker::runAll();
10、启动、停止、查看状态
# Start
# for debug mode
php server.php start
# for daemon mode
php server.php start -d
# Stop
php server.php stop
# Status
php server.php status
11、客户端 client.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document - xushanxiang.com</title> </head> <body> <script src='https://cdn.bootcss.com/socket.io/2.0.3/socket.io.js'></script> <script> // 如果服务端不在本机,请把127.0.0.1改成服务端ip var socket = io('http://127.0.0.1:3120'); // 当连接服务端成功时触发connect默认事件 socket.on('connect', function(){ console.log('connect success'); }); </script> </body> </html>
发表回复