how react js acts as a websocket client?

前端 未结 3 1768
野的像风
野的像风 2020-12-31 05:44

I want to create a Websocket based client-server Application. In that I\'m created node js websocket server which is waiting for the clients. Now I want to create react js w

3条回答
  •  無奈伤痛
    2020-12-31 06:13

    In your react Project folder in App.js add a websocket connection & listen for the messages coming from the websocket server.

    class App extends React.Component{
      constructor(){
       super();
        this.state={
          endpoint:"ws://localhost:1234",
          messages:[]
         }
       }
    
      componentDidMount(){
      //initialize connection
       const ws = new WebSocket(this.state.endpoint)
        ws.onopen = () =>{
         //send any msg from Client if needed
           ws.send(JSON.stringify(temp))
      }
       //save whatever response from client
        ws.onmessage = evt =>{
         this.setState({
          message:this.state.message.concat(evt.data)
        })
      }
     }
     render(){
     return(
     

    {this.state.message.map(items=>

  • {items}
  • )}

    )}

    }

提交回复
热议问题