|
昨天开始学的Swoole
作为学习路上的一个记录吧
也给还没开始学Swoole的同学提供一个Swoole基础的小案例
基于Swoole的Websocket
Websocket部分
- <?php
- /**
- * Class SwooleWs
- * WebSocket Study
- */
- class SwooleWs{
- protected $ws;
- public function __construct()
- {
- $this->ws = new Swoole\WebSocket\Server("0.0.0.0", 9501);
- //连接
- $this->ws->on('open',[$this,'open']);
- //消息发送
- $this->ws->on('message',[$this,'message']);
- //关闭
- $this->ws->on('close',[$this,'close']);
- //启动
- $this->ws->start();
- }
- public function open($server, $request)
- {
- echo "客户端{$request->fd}已连接\n";
- }
- public function message($server, $frame)
- {
- foreach ($server->connections as $fd){
- $frame->fd == $fd ? $oop="我:" : $oop = "用户".$frame->fd.":";
- $server->push($fd, $oop.$frame->data);
- }
- }
- public function close($ser, $fd)
- {
- echo "客户端{$fd} 退出\n";
- }
- }
- new SwooleWs();
复制代码
JS部分
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Swoole NO 1</title>
- </head>
- <body>
- <h1 id="state"></h1>
- <input type="text" placeholder="请输入发送内容:" id="msg">
- <input type="button" value="发送消息" onclick="send()">
- <div id="chat">
- </div>
- </body>
- </html>
- <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
- <script>
- var wsServer = 'ws://你的外网IP:9501';
- var websocket = new WebSocket(wsServer);
- websocket.onopen = function (evt) {
- $('#state').text('恭喜,服务器连接成功');
- };
- websocket.onclose = function (evt) {
- console.log("Disconnected");
- };
- websocket.onmessage = function (evt) {
- $('#chat').append("<p>"+evt.data+"</p>");
- };
- websocket.onerror = function (evt, e) {
- $('#state').text('服务器连接失败');
- };
- function send(){
- let msg = $('#msg').val();
- websocket.send(msg);
- }
- </script>
复制代码
|
1. 本站所有资源来源收集于用户上传和网络,如有侵权请邮件联系站长!
2. 本站联系邮箱:1784605674@qq.com
3. 需要定制软件/网站/各类程序开发,联系站长QQ:1784605674
|