本文将从实例出发,教大家怎么使用swoole快速搭建服务器,实现简易聊天。
我使用的环境是
服务端直接copy文档实例并添加自己的业务逻辑
123php-fpm : 7.2.8
nginx : 1.19.6
redis : 5.0.3
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 | $this ->server = new Server( "0.0.0.0" , 9501); $this ->server->set([ 'worker_num' => 1, 'heartbeat_check_interval' => 30, 'heartbeat_idle_time' => 62, 'daemonize' => true, //开启守护进程 'log_file' => '/opt/local/swoole_log/ws_log' ]); $this ->server->on( 'message' , function (Server $server , $frame ) { echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n" ; $object = json_decode( $frame ->data, true); if (! empty ( $object )) { $this ->push( $object ); } $this ->disposeMember( $frame ->fd, true, $object [ 'nickname' ]); }); $this ->server->on( 'close' , function ( $ser , $fd ) { echo "client {$fd} closed\n" ; $nickname = $this ->disposeMember( $fd , false); if (! empty ( $nickname )) { $this ->push([ 'nickname' => $nickname , 'content' => '退出了聊天室' , 'type' => 1, 'time' => date ( "Y-m-d H:i:s" , time()) ], null, $fd ); } }); $this ->server->start(); |
客服端使用js的websocket接口并添加自己的业务逻辑
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 | initWebSocket: function () { var that = this; try { if (window.WebSocket){ that.server = new WebSocket(that.ws_server); // 连接 that.server.addEventListener( 'open' , (event) => { // console.log(that.lockReconnect); if (that.is_newserver) { that.sendMessageCopy(1, '进入了聊天室' ); that.is_newserver = false; }; that.start(); }); // 关闭 that.server.addEventListener( 'close' , (event) => { console.log( 'close' ); that.reconnect(); }); that.server.onmessage = function (evt) { that.reset(); let test = JSON.parse(evt.data); that.chatList.push({ type : test.type, nickname: test.nickname, content : test.content, avatar : test.avatar, time : test.time }); console.log( 'Retrieved data from server: ' + evt.data); }; that.server.onerror = function (evt, e) { console.log( 'Error occured: ' + evt.data); }; } else { console.log( "您的浏览器不支持WebSocket" ); } } catch(e) { //重连 reconnect(that.ws_server); } }, |
以上就是“实例分享||使用swoole快速搭建websocket,实现简单聊天”的详细内容,想要了解更多swoole教程欢迎持续关注编程学习网
扫码二维码 获取免费视频学习资料
- 本文固定链接: http://phpxs.com/post/8803/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取