首页 > 解决方案 > 第一次使用 webSocket(在 React 中),我得到“失败:连接建立错误:net::ERR_NAME_NOT_RESOLVED

问题描述

我正在关注文档,但我得到“失败:连接建立错误”并且无法弄清楚原因。

    class App extends React.Component {
    
       ws = new WebSocket("ws:https://sampleserver.com");
    
      componentDidMount = () => {
        this.ws.onopen = () => {
          // on connecting, do nothing but log it to the console
          console.log('connected',this.ws)
          }
this.ws.onmessage = evt => {
        // listen to data sent from the websocket server
        const message = JSON.parse(evt.data)
        this.setState({dataFromServer: message})
        console.log(message)
        }

        this.ws.onclose = () => {
        console.log('disconnected')
        // automatically try to reconnect on connection loss

        }
       }

标签: reactjswebsocket

解决方案


推荐阅读