分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

websocket推送

发布时间:2023-09-06 02:26责任编辑:白小东关键词:websocket

<!DOCTYPE HTML>
<html>
<head>
???<title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> ???<button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script src="https://lib.baomitu.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
???var socket = null;

???//判断当前浏览器是否支持WebSocket
???if(‘WebSocket‘ in window){
???????socket = new WebSocket("ws://localhost:9999/websocket/GRAPH");
???}
???else{
???????alert(‘Not support websocket‘)
???}

???//打开事件
???socket.onopen = function() {
???????console.log("Socket 已打开");
???????//socket.send("这是来自客户端的消息" + location.href + new Date());
???};
???//获得消息事件
???socket.onmessage = function(msg) {
???????console.log(msg.data);

???????var arr = JSON.parse(msg.data);
???????console.log(arr.student);
???????//发现消息进入 ???开始处理前端触发逻辑
???};
???//关闭事件
???socket.onclose = function() {
???????console.log("Socket已关闭");
???};
???//发生了错误事件
???socket.onerror = function() {
???????alert("Socket发生了错误");
???????//此时可以尝试刷新页面
???}
???//离开页面时,关闭socket
???//jquery1.8中已经被废弃,3.0中已经移除
???// $(window).unload(function(){
???// ????socket.close();
???//});
???
???function send() {
???????$.ajax({
???????????url: "http://localhost:8084/socket/push/20?message=ccccccccccc",
???????????type:‘get‘,
???????????dataType : "json",
???????????cache: false,
???????????success: function(data) {
???????????????console.log(data)
???????????},
???????????error: function (error) {
???????????????console.log(error)
???????????}
???????})
???}
</script>
</html>

websocket推送

原文地址:https://www.cnblogs.com/xieyongbin/p/10123341.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved