123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- use Workerman\Worker;
- //require_once __DIR__ . '/Workerman/Autoloader.php';
- //use Workerman\Autoloader;
- require_once __DIR__ . '/vendor/workerman/workerman/Autoloader.php';
- $worker = new Worker('ws://127.0.0.1:2346');
- $worker->count = 4;
- $worker->onConnect = function($connection)
- {
- echo $connection->id;
- };
- $worker->onMessage = function($connection, $data)
- {
- // 向浏览器发送hello world
- $connection->send('hello world');
- // 客户端传递的是json数据
- $message_data = json_decode($data, true);
- if(!$message_data)
- {
- return ;
- }
- // 根据类型执行不同的业务
- switch($message_data['type'])
- {
- // 客户端回应服务端的心跳
- case 'pong':
- return ;
- // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室
- case 'login':
- if(!isset($message_data['room_id']))
- {
- throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
- }
- // 判断当前客户端是否已经验证,即是否设置了uid
- if(!isset($connection->uid))
- {
- // 没验证的话把第一个包当做uid(这里为了方便演示,没做真正的验证)
- $connection->uid = $message_data['client_name'];
- /* 保存uid到connection的映射,这样可以方便的通过uid查找connection,
- * 实现针对特定uid推送数据
- */
- $worker = $this->worker;
- foreach($worker->connections as $conn)
- {
- $conn->send("{'type':'login','data':'".$message_data['client_name']."登陆成功'}");
- }
- }
- case 'say':
- return;
- }
- };
- // 运行worker
- Worker::runAll();
|