|
|
@@ -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]);
|
|
|
+ }
|
|
|
+
|
|
|
+}
|