微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/react/300757.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐