imsocket.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace app\api\imsocket;
  3. use think\facade\Db;
  4. use think\worker\Server;
  5. use GatewayWorker\Lib\Gateway;
  6. class imsocket extends Server
  7. {
  8. protected $socket = 'websocket://0.0.0.0:6550';
  9. protected $uidConnnections = array();
  10. public function __construct()
  11. {
  12. parent::__construct();
  13. }
  14. public function onConnect($connection){
  15. $msg=['type'=>'conn','msg'=>'连接服务器成功'];
  16. $connection->send(json_encode($msg));
  17. }
  18. public function onMessage($connection,$data)
  19. {
  20. $arr = json_decode($data);
  21. //绑定用户
  22. if($arr->type == "bind" && !isset($connection->uid)){
  23. $connection->uid = $arr->uid;
  24. //保存uid到connection的映射,实现针对特定uid的推送
  25. $this->worker->uidConnections[$connection->uid]=$connection;
  26. }
  27. //聊天
  28. if($arr->type=="text"){
  29. if(isset($this->worker->uidConnections[$arr->to_user_id])){
  30. $conn= $this->worker->uidConnections[$arr->to_user_id];
  31. $conn->send($data);
  32. }else{
  33. //先返回给发送者错误信息
  34. $conn2= $this->worker->uidConnections[$arr->from_user_id];
  35. $msg=['type'=>'error','msg'=>'对方不在线'];
  36. $conn2->send(json_encode($msg));
  37. }
  38. }
  39. }
  40. public function onClose($connection){
  41. unset($this->worker->uidConnections[$connection->uid]);
  42. }
  43. }