49107199@qq.com пре 4 година
родитељ
комит
e4a59d51d9
2 измењених фајлова са 58 додато и 7 уклоњено
  1. 7 7
      .env
  2. 51 0
      app/api/imsocket/imsocket.php

+ 7 - 7
.env

@@ -14,13 +14,13 @@ CHARSET = utf8
 DEBUG = false
 
 [CACHE]
-DRIVER = redis
-
-[REDIS]
-HOSTNAME = 47.112.222.163
-HOSTPORT = 6379
-PASSWORD = derkj&6688
-SELECT = 2
+#DRIVER = redis
+#
+#[REDIS]
+#HOSTNAME = 47.112.222.163
+#HOSTPORT = 6379
+#PASSWORD = derkj&6688
+#SELECT = 2
 
 [LANG]
 default_lang = zh-cn

+ 51 - 0
app/api/imsocket/imsocket.php

@@ -0,0 +1,51 @@
+<?php
+namespace app\api\imsocket;
+use think\facade\Db;
+use think\worker\Server;
+use GatewayWorker\Lib\Gateway;
+class imsocket extends Server
+{
+    protected $socket = 'websocket://0.0.0.0:2345';
+    protected $uidConnnections = array();
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    public function  onConnect($connection){
+        $msg=['type'=>'conn','msg'=>'连接服务器成功'];
+
+        $connection->send(json_encode($msg));
+    }
+
+    public function onMessage($connection,$data)
+    {
+        $arr = json_decode($data);
+
+        //绑定用户
+        if($arr->type == "bind" && !isset($connection->uid)){
+            $connection->uid = $arr->uid;
+            //保存uid到connection的映射,实现针对特定uid的推送
+           $this->worker->uidConnections[$connection->uid]=$connection;
+
+        }
+        //聊天
+        if($arr->type=="text"){
+            if(isset($this->worker->uidConnections[$arr->to_user_id])){
+                $conn= $this->worker->uidConnections[$arr->to_user_id];
+                $conn->send($data);
+            }else{
+                //先返回给发送者错误信息
+                $conn2= $this->worker->uidConnections[$arr->from_user_id];
+                $msg=['type'=>'error','msg'=>'对方不在线'];
+                $conn2->send(json_encode($msg));
+            }
+
+        }
+
+    }
+    public function onClose($connection){
+        unset($this->worker->uidConnections[$connection->uid]);
+    }
+
+}