【问题标题】:how react js acts as a websocket client?react js如何充当websocket客户端?
【发布时间】:2016-11-02 11:42:35
【问题描述】:

我想创建一个基于 Websocket 的客户端-服务器应用程序。在那里,我创建了等待客户端的节点 js websocket 服务器。现在我想创建 react js websocket 客户端。我使用 react js 作为 websocket,因为我必须连续渲染元素,服务器将其作为简单的文本消息发送。

我对将 react js 实现为 websocket 客户端感到震惊。它应该如何作为 websocket 客户端工作,以及它将如何向 websocket 服务器发送请求,就像这样:

'ws://localhost:1234'

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

【问题讨论】:

标签: reactjs websocket


【解决方案1】:

所以一个没有太多开销的非常基本的例子需要两件事:

  1. 一个引用 websocket 连接的组件

  2. 连接上的事件侦听器,用于更新组件的状态 当消息到达时

演示: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>;
  }
};

【讨论】:

  • - 嘿,听起来不错...但我正面临 糟糕的 JSFiddle 配置,请 fork 原始 React JSFiddle 错误,我认为我的结构无效,请告诉我如何为我的 React 应用程序构建结构?即 html,js,webpack.config.js & package.json
  • 你从哪里得到这个错误?在我的答案中链接的演示小提琴上?
  • 是的...我只是放置 js 代码 n 更改 ws url 并且在 html 中我们正在使用这个
  • 对于上面的 jsfiddle 链接有问题的任何人。单击该链接后,您可以看到一个值为“Javascript”的 HTML Select。将此选择翻转为“React”,然后单击页面左上角的“运行”按钮。这就是我让示例为我工作的方式。
  • @Frito 更新了我的答案中的链接。小提琴是很久以前通过分叉“React Base Fiddle”制作的(我认为当时 jsfiddle 中没有预定义的 React 配置)。谢谢!
【解决方案2】:

只需从服务器端创建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 个会话进行通信。

【讨论】:

  • 此答案仅适用于纯 JavaScript。问题即将把这个答案放到reactjs中。所以你没有回答这个问题。
【解决方案3】:

在 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>
)}

}

【讨论】:

    【解决方案4】:

    我在这里留下一个功能示例(以上都是对象...)

    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()
        }
    }, [])
    

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-19
      • 2016-01-31
      • 1970-01-01
      • 2020-03-24
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多