start.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. use Workerman\Worker;
  3. //require_once __DIR__ . '/Workerman/Autoloader.php';
  4. //use Workerman\Autoloader;
  5. require_once __DIR__ . '/vendor/workerman/workerman/Autoloader.php';
  6. $worker = new Worker('ws://127.0.0.1:2346');
  7. $worker->count = 4;
  8. $worker->onConnect = function($connection)
  9. {
  10. echo $connection->id;
  11. };
  12. $worker->onMessage = function($connection, $data)
  13. {
  14. // 向浏览器发送hello world
  15. $connection->send('hello world');
  16. // 客户端传递的是json数据
  17. $message_data = json_decode($data, true);
  18. if(!$message_data)
  19. {
  20. return ;
  21. }
  22. // 根据类型执行不同的业务
  23. switch($message_data['type'])
  24. {
  25. // 客户端回应服务端的心跳
  26. case 'pong':
  27. return ;
  28. // 客户端登录 message格式: {type:login, name:xx, room_id:1} ,添加到客户端,广播给所有客户端xx进入聊天室
  29. case 'login':
  30. if(!isset($message_data['room_id']))
  31. {
  32. throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
  33. }
  34. // 判断当前客户端是否已经验证,即是否设置了uid
  35. if(!isset($connection->uid))
  36. {
  37. // 没验证的话把第一个包当做uid(这里为了方便演示,没做真正的验证)
  38. $connection->uid = $message_data['client_name'];
  39. /* 保存uid到connection的映射,这样可以方便的通过uid查找connection,
  40. * 实现针对特定uid推送数据
  41. */
  42. $worker = $this->worker;
  43. foreach($worker->connections as $conn)
  44. {
  45. $conn->send("{'type':'login','data':'".$message_data['client_name']."登陆成功'}");
  46. }
  47. }
  48. case 'say':
  49. return;
  50. }
  51. };
  52. // 运行worker
  53. Worker::runAll();