配置
'wsServer' => [
'class' => WebSocketServer::class,
'port' => 18308,
'listener' => [
// 'rpc' => bean('rpcServer'),
// 'tcp' => bean('tcpServer'),
],
'on' => [
// ws默认支持http请求
// Enable http handle
SwooleEvent::REQUEST => bean(RequestListener::class),
// Enable task must add task and finish event
SwooleEvent::TASK => bean(TaskListener::class),
SwooleEvent::FINISH => bean(FinishListener::class)
],
'debug' => 1,
// 'debug' => env('SWOFT_DEBUG', 0),
/* @see WebSocketServer::$setting */
'setting' => [
'task_worker_num' => 6,
'task_enable_coroutine' => true,
'worker_num' => 6,
'log_file' => alias('@runtime/swoole.log'),
// 'open_websocket_close_frame' => true,
],
],
启动
【ws默认支持http请求,http请求的端口和ws端口都是 18308】
php swoftcli.phar run -c ws:start -b bin/swoft -d
前端请求代码
// 建立链接,这里请求的是swoft-ws的chat模型
new WebSocket('ws://192.168.0.155:18308/chat')
// swoft接收的数据格式
var send = {
"cmd": route, // 请求控制器的路由名
"data": { // 发送自定义的数据
"msg" : send_msg,
"callback" : {
"active": fn,
"param" : param
}
},
}
// json转字符串
send = JSON.stringify(send)
// 发送
ws.send(send)
swoft的目录结构
ws控制器路由注解
namespace App\WebSocket\Chat;
use Swoft\Session\Session;
use Swoft\WebSocket\Server\Annotation\Mapping\MessageMapping;
use Swoft\WebSocket\Server\Annotation\Mapping\WsController;
use Swoft\Redis\Redis;
use App\WebSocket\Chat\BaseController;
use Swoft\Db\DB;
/**
* Class HomeController
*
* @WsController()
*/
class HomeController extends BaseController
{
/**
* Message command is: 'home.index'
*
* @return void
* @MessageMapping()
*/
public function index(): void
{
// Session::current()->push('hi, this is home.index');
// 给指定客户端发送消息
// \server()->sendTo($fd, '给指定客户端发送消息');
// 给指定部分客户端发送消息
// \server()->sendToSome('给指定部分客户端发送消息', [$fd0, $fd1]);
// 给所有人发送消息
\server()->sendToAll('给所有人发送消息');
}
}