Skip to content

Commit e44d742

Browse files
committed
update: json 字符串输出
1 parent 6d458c6 commit e44d742

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

laravel/app/Services/WebSocketService.php

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,16 @@ public function onOpen($server, $request)
3737
while (true) {
3838
// 3. 输出完成率
3939
$rate = MultithreadingRepository::getInstent()->completionRate($req['id']);
40-
$server->push($request->fd, $rate.'%');
40+
$data = $this->outJson(200, ['rate' => $rate]);
41+
$server->push($request->fd, $data);
4142
sleep(3);
4243

4344
if ($rate >= 100) {
4445
break;
4546
}
4647
}
4748
} else {
48-
$server->push($request->fd, '100%');
49+
$server->push($request->fd, $this->outJson(200, ['rate' => '100']));
4950
}
5051

5152
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
@@ -62,4 +63,22 @@ public function onClose($server, $fd, $reactorId)
6263
{
6364
// throw new \Exception('an exception');// 此时抛出的异常上层会忽略,并记录到Swoole日志,需要开发者try/catch捕获处理
6465
}
66+
67+
/**
68+
* 处理输出
69+
*
70+
* @param int $code
71+
* @param array $data
72+
* @param string $reason
73+
*
74+
* @return array
75+
*/
76+
public function outJson($code = 200, $data = [], $reason = 'success')
77+
{
78+
if ($reason === 'success') {
79+
$reason = config('errorCode.'.$code.'.reason') ?? 'success';
80+
}
81+
82+
return json_encode(['code' => $code, 'reason' => $reason, 'data' => $data], JSON_UNESCAPED_UNICODE);
83+
}
6584
}

0 commit comments

Comments
 (0)