赞
踩
"sockjs-client": "^1.5.0",
"stompjs": "^2.3.3",
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
// websocket initWebSocket () { this.connect() const self = this // 断开重连机制,尝试发送消息,捕获异常发生时重连 this.timer = setInterval(() => { try { console.log('成功') } catch (err) { console.log('断线了: ' + err) self.connect() } }, 10000) }, connect () { // 连接服务端提供的通信接口,连接以后才可以订阅广播消息和个人消息 const sock = new SockJS('http://110.61.76.221:8090/monitor') // 获取STOMP子协议的客户端对象 this.stompClient = Stomp.over(sock) // const token = sessionStorage.getItem('cookieaccess_token') // 向服务器发起websocket连接 this.stompClient.connect({}, (message) => { this.subscribe() }, error => { this.initWebSocket() }) }, sendMessage () { // 发送消息 this.stompClient.send('/app/chat', {}, JSON.stringify({})) }, // 断开连接 disconnect () { if (this.stompClient !== null) { this.stompClient.disconnect() console.log('Disconnected') } }, subscribe () { // 订阅公告 const _this = this this.stompClient.subscribe('/topic/chat', function (msg) { const obj = JSON.parse(msg.body) } }) },
<%@ page language="java" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>Java后端WebSocket的Tomcat实现</title> </head> <script src="http://code.jquery.com/jquery-latest.js"></script> <body> Welcome<br /><input id="text" type="text" /> <button onclick="send()">发送消息</button> <br /> <input id="b" type="text" /> <!-- 这里用于注册不同的clientId, 多个webSocket客户端只能同步收到相同clientId的消息 --> <button onclick="connect()">连接</button> <hr /> <button onclick="closeWebSocket()">关闭WebSocket连接</button> <hr /> <div id="message"></div> </body> <script type="text/javascript"> var websocket = null; function connect() { //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { var value = $("#b").val(); websocket = new WebSocket("ws://localhost:8080/ws/websocket/" + value); //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } } else { alert('当前浏览器 Not support websocket') } }; //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); } //发送消息 function send() { var message = document.getElementById('text').value; websocket.send(message); } </script> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。