reactjs react js如何作为一个WebSocket客户端?

liwlm1x9  于 2023-03-01  发布在  React
关注(0)|答案(5)|浏览(127)

我想创建一个基于WebSocket的客户端-服务器应用程序。在这里我创建了node js websocket服务器,它正在等待客户端。现在我想创建react js websocket客户端。我使用react js作为websocket,因为我必须不断地呈现服务器以简单文本消息形式发送的元素。
我对react js作为一个WebSocket客户端的实现感到震惊。它应该如何作为一个websocket客户端工作,以及它将如何发送请求到websocket服务器,就像这样:

'ws://localhost:1234'

我想了解更多关于WebSocket客户端的信息,也想解决这个问题?

6tqwzwtp

6tqwzwtp1#

因此,一个没有太多开销的非常基本的示例将需要两件事:
1.引用websocket连接的组件
1.连接上的事件侦听器,用于在消息到达时更新组件的状态
演示:http://jsfiddle.net/69z2wepo/47360/
演示(2019年):http://jsfiddle.net/643atLce/

class Echo extends React.Component {
    constructor(props){
    super(props);
    this.state = { messages : [] }
  }

  componentDidMount(){
    // this is an "echo" websocket service
    this.connection = new WebSocket('wss://echo.websocket.org');
    // listen to onmessage event
    this.connection.onmessage = evt => { 
      // add the new message to state
        this.setState({
        messages : this.state.messages.concat([ evt.data ])
      })
    };

    // for testing purposes: sending to the echo service which will send it back back
    setInterval( _ =>{
        this.connection.send( Math.random() )
    }, 2000 )
  }

  render() {
    // slice(-5) gives us the five most recent messages
    return <ul>{ this.state.messages.slice(-5).map( (msg, idx) => <li key={'msg-' + idx }>{ msg }</li> )}</ul>;
  }
};
rggaifut

rggaifut2#

只需从服务器端创建rest程序,然后在网页上创建连接即可。

var connection = new WebSocket('ws://localhost/echo', ['soap', 'xmpp']);

opening the connection 
connection.onopen = function () {
  connection.send('Ping'); // 
};

connection.onerror = function (error) {
  console.log('WebSocket Error ' + error);
};

//to receive the message from server
connection.onmessage = function (e) {
  console.log('Server: ' + e.data);
};

// Sending String  
connection.send('your message');

在服务器端你会得到会话和消息,所以你可以做N个会话的通信。

xwbd5t1u

xwbd5t1u3#

在App.js的react Project文件夹中添加一个WebSocket连接并监听来自websocket服务器的消息。

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(
 <div>
 <p>{this.state.message.map(items=><li>{items}</li>)}</p>
 </div>
)}

}

w8f9ii69

w8f9ii694#

我在这里留下一个函数示例(以上所有都是对象...)

const client = new WebSocket(ws://stream.marketpricesfun.com)
const [cottonPrice, setCottonPrice] = useState(0)

useEffect(() => {
    client.onopen = () => {
        client.send('{"topic": "subscribe", "to": "newPrices"}')
    }

    client.onmessage = (message) => {
        if (message.data) {
            const parsedData = JSON.parse(message.data)

            setCottonPrice(parsedData.cotton.price)
        }
    }

    return () => {
        client.close()
    }
}, [])
ig9co6j1

ig9co6j15#

我们中的一些人使用钩子来处理Websocket连接,但这里是我的,solution很简单,一旦你的应用程序变得更大,你就不会在未来的情况下陷入混乱

相关问题