<?php
use \think\swoole\facade\Websocket;
class Socket
{
public function test () {
Websocket::on('tomsg', function (\think\swoole\Websocket $websocket, $data) {
$websocket->broadcast()->to('room1')->emit('getmsg', $data);
});
Websocket::on('joinroom', function (\think\swoole\Websocket $websocket, $data) {
echo '加入房间1'.PHP_EOL;
$websocket->join('room1');
});
}
}
$ws = new Socket;
$ws->test();这是websocket.php下面是客户端代码,两个页面相同的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>swoole test</title>
</head>
<body>
<script src="/static/socket.io-client/dist/socket.io.js"></script>
<script>
const socket = io('http://swoole.xxx.cn:12300', {transports: ['websocket']});
socket.emit("joinroom", "1")
socket.on("getmsg",function(res){console.log(res)});
</script>
</body>
</html> 最佳答案