<!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