Programing

React Native(원본 반응) 기능이 있는 WebSockets를 사용하는 올바른 방법

c10106 2022. 4. 7. 21:08
반응형

React Native(원본 반응) 기능이 있는 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);

모든 것이 잘 작동하지만 메시지를 보내기 위해 버튼을 누르면 다음과 같은 오류가 발생한다.

메시지를 보낼 수 없음.알 수 없는 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에 의해 생성된 프로젝트)를 기반으로 공용 웹셋 서버에 연결하는 RN 0.45wss://echo.websocket.org/내 안드로이드에서는 잘 작동하고 버튼을 누르면 웹셋 서버의 에코 메시지를 볼 수 있다.

import React, { Component } from 'react';

import {
    StyleSheet,
    Text,
    View,
    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',
            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>
        );
    }
}


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

문서에 따라 상태를 추가해야 함connected구성 요소에 연결하십시오.그리고 어떤 것이라도 보내면connected상태는 진실이다.

export default class raspberry extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      connected: false
    };
    this.socket = new WebSocket('ws://127.0.0.1:3000');
    this.socket.onopen = () => {
      this.setState({connected:true})
    }; 
    this.emit = this.emit.bind(this);
  }

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

내가 몇 가지 조사를 한 후에 나는 웹소켓이

new WebSocket("ws://10.0.2.2:PORT/")

어디에10.0.2.2을 의미하다localhost

참조URL: https://stackoverflow.com/questions/44088058/proper-way-of-using-websockets-with-react-native

반응형