当前位置: 首页 > Web前端 > HTML5

H5Server-SentEvent-单向消息传递

时间:2023-04-05 23:00:14 HTML5

虽然我以前知道这个技术,但我没有尝试过。今天就记录在这里。我们先看看W3school是怎么说的。也就是说可以做一些简单的消息推送。这是我的代码:html页面倒计时

开启签到结束登录
js代码:varsource,message,timer;/***打开签到-开始检查服务器是否有更新*/$("#open").click(function(){countdown();if(typeof(EventSource)!=="undefined"){source=newEventSource("http://10.3.140.139:8082/index/test/getuser");source.onmessage=function(event)//收到消息{message=event.data;varlen=message.length;如果(len>0){message=JSON.parse(消息);$(".handle_messagetr").append(code(message['head_pic'],message['username']));}};}else{layer.msg('抱歉,您的浏览器不支持服务器发送的事件...');}});/***关闭监听器*/$("#close").click(function(){cz_close();});/***关闭监听操作*/functioncz_close(){timer=$(".paging").val();清除超时(计时器);$('#test').html('签到结束');来源.close();$.post("http://10.3.140.139:8082/index/test/clearcache");layer.msg('停止监听服务器更新');}/***添加代码*@returns{string}*/functioncode(pic,name){varcode=''+''+''+name+'

'+'';返回码;}/***倒计时*/functioncountdown(){layui.use('util',function(){varutil=layui.util,serverTime=newDate().getTime(),endTime=serverTime+(2*(60*1000));util.countdown(endTime,serverTime,function(date,serverTime,timer){$(".paging").val(timer);varstr=date[2]+'minute'+date[3]+'second';if(date[0]==0&&date[1]==0&&date[2]==0&&date[3]==0){clearTimeout(timer);//清除定时器cz_close();}else{$('#test').html('剩余时间:'+str);}});});}php代码:/***@returnmixed*学生登录页面*/publicfunctionindex(){return$this->fetch();}/***@returnmixed*老师打开签到页面*/publicfunctiondemo(){return$this->fetch();}/***将登录学生加入缓存*/publicfunctionpost(){if($_POST){$img=self::curlInfo();$_POST['head_pic']=$img;$信息=json_encode($_POST);缓存::设置('user_info',$info);}}/***从缓存中获取用户*/publicfunctiongetUser(){//获取并清除当前缓存$info=Cache::pull('user_info');////服务器事件标准规定(设置MIME类型为text/event-stream)header('Content-Type:text/event-stream');////告诉网络服务器关闭网络缓存header('Cache-Control:no-cache');回声“数据:{$信息}\n\n”;//立即发送数据(而不是先缓存起来,等PHP代码执行完再发送)flush();}/***清除缓存*/publicfunctionclearCache(){Cache::clear();}/***@returnmixed*获取用户的随机头像*/protectedfunctioncurlInfo(){$url='https://api.66mz8.com/api/rand.pic.php?type=%E4%B8%AA%E6%80%A7&return=json';$curl=curl_init();//初始化CURL句柄curl_setopt($curl,CURLOPT_URL,$url);curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);curl_setopt($curl,CURLOPT_HTTPGET,真);curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);$output=curl_exec($curl);curl_close($curl);$info=json_decode($output,true);$img=$info['imgurl'];返回$img;}参考链接:http://www.w3school.com.cn/ht...http://www.hangge.com/blog/ca...

猜你喜欢