reactjs – 使用React Native的WebSockets的正确方法

前端之家收集整理的这篇文章主要介绍了reactjs – 使用React Native的WebSockets的正确方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是React Native的新手,但对React非常熟悉.作为一个初学者,我正在寻找在云服务器之间建立连接并使用websockets建立反应原生,正如我在文档中看到的那样.不幸的是,没有像样的例子可以帮助我.这就是我到目前为止所做的一切:
import React,{ Component } from 'react';

import {
  AppRegistry,StyleSheet,Text,View,Button
} from 'react-native';

export default class raspberry extends Component {
  constructor(props) {
    super(props);

    this.state = { open: false };
    this.socket = new WebSocket('ws://127.0.0.1:3000');
    this.emit = this.emit.bind(this);
  }

  emit() {
    this.setState(prevState => ({ open: !prevState.open }))
    this.socket.send("It worked!")
  }

  render() {

    const LED = {
      backgroundColor: this.state.open ? 'lightgreen' : 'red',height: 30,position: 'absolute',flexDirection: 'row',bottom: 0,width: 100,height: 100,top: 120,borderRadius: 40,justifyContent: 'space-between'

    }

    return (
      <View style={styles.container}>
        <Button
          onPress={this.emit}
          title={this.state.open ? "Turn off" : "Turn on"}
          color="#21ba45"
          accessibilityLabel="Learn more about this purple button"
        />
        <View style={LED}></View>
      </View>
    );
  }

  componentDidMount() {
    this.socket.onopen = () => socket.send(JSON.stringify({ type: 'greet',payload: 'Hello Mr. Server!' }))
    this.socket.onmessage = ({ data }) => console.log(JSON.parse(data).payload)
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: {
    fontSize: 20,textAlign: 'center',margin: 10,instructions: {
    textAlign: 'center',color: '#333333',marginBottom: 5,});

AppRegistry.registerComponent('raspberry',() => raspberry);

一切正常,但当我按下按钮发送消息时,这是我得到的错误

Cannot send a message. Unknown WebSocket id 1

我还用一个js客户端做了一个测试,一切都很顺利..看看我怎么能得到这个固定的或一些例子来源我可以搞清楚.

改变代码
socket.send(JSON.stringify({ type: 'greet',payload: 'Hello Mr. Server!' }))

this.socket.send(JSON.stringify({ type: 'greet',payload: 'Hello Mr. Server!' }))

它应该工作.

这是我的代码,根据您的代码和RN 0.45(以及由create-react-native-app生成的项目)进行测试,连接到公共websocket服务器wss://echo.websocket.org/,在我的android上运行很好,我按下按钮后可以看到websocket服务器的回显消息.

import React,{ Component } from 'react';

import {
    StyleSheet,Button
} from 'react-native';

export default class App extends React.Component {

    constructor() {
        super();

        this.state = {
            open: false
        };
        this.socket = new WebSocket('wss://echo.websocket.org/');
        this.emit = this.emit.bind(this);
    }

    emit() {
        this.setState(prevState => ({
            open: !prevState.open
        }))
        this.socket.send("It worked!")
    }

    componentDidMount() {
        this.socket.onopen = () => this.socket.send(JSON.stringify({type: 'greet',payload: 'Hello Mr. Server!'}));
        this.socket.onmessage = ({data}) => console.log(data);
    }

    render() {

        const LED = {
            backgroundColor: this.state.open
            ? 'lightgreen'
            : 'red',justifyContent: 'space-between'
        }

        return (
            <View style={styles.container}>
                <Button onPress={this.emit} title={this.state.open
        ? "Turn off"
        : "Turn on"} color="#21ba45" accessibilityLabel="Learn more about this purple button"/>
                <View style={LED}></View>
            </View>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,backgroundColor: '#F5FCFF'
    },welcome: {
        fontSize: 20,margin: 10
    },instructions: {
        textAlign: 'center',marginBottom: 5
    }
});

猜你在找的React相关文章