1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SocketServer extends Command {
protected $signature = 'swoole:server';
protected $description = 'swoole服务端,用于开单的消息转发';
public function __construct() { parent::__construct(); }
public function handle() { $ws = new \Swoole\WebSocket\Server("127.0.0.1", 9501); $ws->on('open', function ($ws, $request) { logger()->channel('wss_open')->info($request->fd . ' socket 连接'); $get = $request->get; if ($get) { foreach ($get as $key => $value) { logger()->channel('wss_open')->info($value); $this->setFid($value, $request->fd); } } $ws->push($request->fd, json_encode(['status' => 1, 'message' => '连接成功'], 256)); });
$ws->on('message', function ($ws, $frame) { $data = json_decode($frame->data, true); logger()->channel('wss_message')->info($frame->fd . ' socket 连接', $data); if ($data) { $su = $this->getFid($data['to']); if ($ws->exist($su)) { logger()->channel('wss_message')->info('发送成功'); $ws->push($su, json_encode([ 'data' => $data['data'], 'status' => 1 ], 256)); } else { logger()->channel('wss_message')->info('发送失败'); $ws->push($frame->fd, json_encode(['status' => 0, 'message' => '找不到目标连接'], 256)); } } });
$ws->on('close', function ($ws, $fd) { $this->delFid($fd); }); $ws->start(); }
public function setFid($uid, $fid) { $client = new \Predis\Client(); $client->hset('uid', $uid, $fid); }
public function getFid($uid) { $client = new \Predis\Client(); return $client->hget('uid', $uid); }
public function delFid($fid) { $client = new \Predis\Client(); $uids = $client->hgetall('uid'); foreach ($uids as $uid => $fd) { if ($fid == $fd) { $client->hdel('uid', $uid); echo '删除' . $uid; } } } }
|