react js 如何充当 websocket 客户端? [英] how react js acts as a websocket client?

查看:269
本文介绍了react js 如何充当 websocket 客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个基于 Websocket 的客户端-服务器应用程序.我创建了 node js websocket 服务器,它正在等待客户端.现在我想创建 react js websocket 客户端.我将 react js 用作 websocket,因为我必须连续呈现服务器作为简单文本消息发送的元素.

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 websocket client. I'm using react js as a websocket because I have to render elements continuously which server sends as a simple text message.

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

I'm struck at implementing the react js as a websocket client. How it should work as a websocket client and how it will send request to the websocket server just like this :

'ws://localhost:1234'

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

I want to know more about websocket client and also want to solve this issue?

推荐答案

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

So a very basic example without much overhead would require two things:

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

  1. a component with a reference to websocket connection

更新组件状态的连接上的事件监听器当消息到达时

an event listener on the connection that updates the state of the component when a message arrives

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

这篇关于react js 如何充当 websocket 客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆