首先在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>
Logo

前往低代码交流专区

更多推荐