Vue项目中链接websocket,做一个全局通知信息
首先在index.html中加上下面一段代码<script>var websocket = nullvar localHref = window.location.host === 'localhost:9528' ? '线上服务器地址' : window.location.hostlocalStorage.setItem('isOk', '0')...
·
首先在index.html中加上下面一段代码
<script>
var websocket = null
var localHref = window.location.host === 'localhost:9528' ? '线上服务器地址' : window.location.host
if ('WebSocket' in window) {
// websocket = new WebSocket('ws://线上服务器地址/webSocket')
websocket = new WebSocket('ws://线上服务器地址/webSocket')
// websocket = new WebSocket('ws://' + localHref + '/webSocket')
} else {
alert('该浏览器不支持websocket!')
}
websocket.onopen = function(event) {
console.log('建立连接')
}
websocket.onmessage = function(event) {
console.log('socket收到消息', event)
console.log('收到消息:' + event.data)
// alert('收到消息:' + event.data)
}
websocket.onerror = function() {
console.log('websocket通信发生错误!')
}
window.onbeforeunload = function() {
websocket.close()
}
websocket.onclose = function(event) {
console.log('连接关闭')
}
</script>
更多推荐
已为社区贡献11条内容
所有评论(0)