Reactjs 使用带有React Native的WebSocket的正确方法

Reactjs 使用带有React Native的WebSocket的正确方法,reactjs,react-native,websocket,Reactjs,React Native,Websocket,我不熟悉React,但对React非常熟悉。作为一名初学者,我希望在云服务器和react native之间建立连接,正如我在文档中看到的那样。不幸的是,没有一个像样的例子可以帮助我。到目前为止,我只知道这些: import React,{Component}来自'React'; 进口{ 评估学, 样式表, 文本, 看法 按钮 }从“反应本机”; 导出默认类raspberry扩展组件{ 建造师(道具){ 超级(道具); this.state={open:false}; this.socket=ne

我不熟悉React,但对React非常熟悉。作为一名初学者,我希望在云服务器和react native之间建立连接,正如我在文档中看到的那样。不幸的是,没有一个像样的例子可以帮助我。到目前为止,我只知道这些:

import React,{Component}来自'React';
进口{
评估学,
样式表,
文本,
看法
按钮
}从“反应本机”;
导出默认类raspberry扩展组件{
建造师(道具){
超级(道具);
this.state={open:false};
this.socket=newwebsocket('ws://127.0.0.1:3000');
this.emit=this.emit.bind(this);
}
发射(){
this.setState(prevState=>({open:!prevState.open}))
this.socket.send(“成功了!”)
}
render(){
常数LED={
背景颜色:this.state.open?“浅绿色”:“红色”,
身高:30,
位置:'绝对',
flexDirection:'行',
底部:0,
宽度:100,
身高:100,
排名:120,
边界半径:40,
justifyContent:“间距”
}
返回(
);
}
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({
容器:{
弹性:1,
为内容辩护:“中心”,
对齐项目:“居中”,
背景颜色:“#F5FCFF”,
},
欢迎:{
尺寸:20,
textAlign:'中心',
差额:10,
},
说明:{
textAlign:'中心',
颜色:'#333333',
marginBottom:5,
},
});
AppRegistry.registerComponent('raspberry',()=>raspberry);
一切正常,但当我按下按钮发送消息时,我得到的错误是:

无法发送消息。未知WebSocket id 1

我还用一个js客户端做了一个测试,一切都进行得很顺利。我想看看如何修复这个问题,或者找到一些可以解决这个问题的示例源代码

根据需要,将状态
已连接
添加到组件。仅当
connected
状态为true时才发送任何内容

导出默认类raspberry扩展组件{
建造师(道具){
超级(道具);
此.state={
开:错,
连接:false
};
this.socket=newwebsocket('ws://127.0.0.1:3000');
this.socket.onopen=()=>{
this.setState({connected:true})
}; 
this.emit=this.emit.bind(this);
}
发射(){
如果(this.state.connected){
this.socket.send(“成功了!”)
this.setState(prevState=>({open:!prevState.open}))
}
}
}

在我做了一些研究之后,我发现WebSocket应该是

new WebSocket("ws://10.0.2.2:PORT/")
其中
10.0.2.2
表示
localhost

更改代码

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,
    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
    }
});
import React,{Component}来自'React';
进口{
样式表,
文本,
看法
按钮
}从“反应本机”;
导出默认类App扩展React.Component{
构造函数(){
超级();
此.state={
开放:假
};
this.socket=新的WebSocket('wss://echo.websocket.org/');
this.emit=this.emit.bind(this);
}
发射(){
this.setState(prevState=>({
打开:!prevState.open
}))
this.socket.send(“成功了!”)
}
componentDidMount(){
this.socket.onopen=()=>this.socket.send(JSON.stringify({type:'greet',payload:'Hello Mr.Server!'}));
this.socket.onmessage=({data})=>console.log(数据);
}
render(){
常数LED={
背景颜色:this.state.open
“浅绿色”
:“红色”,
身高:30,
位置:'绝对',
flexDirection:'行',
底部:0,
宽度:100,
身高:100,
排名:120,
边界半径:40,
justifyContent:“间距”
}
返回(
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
为内容辩护:“中心”,
对齐项目:“居中”,
背景颜色:“#F5FCFF”
},
欢迎:{
尺寸:20,
textAlign:'中心',
差额:10
},
说明:{
textAlign:'中心',
颜色:'#333333',
marginBottom:5
}
});

如果套接字尚未打开,您是否意外没有关闭它?我来自socket.io,在那里关闭套接字不是一件事,但对于ws,这确实可能是一件事。我回家后会把它们关上的,泰,给我小费!只是想知道,你不使用socket.io有什么原因吗?得到一个未经“验证的错误”知道如何修复吗?这似乎是可行的,我一回到家就会测试它。得到一个未经“验证的错误”知道如何修复吗?这就是在原始帖子中发现并修复实际错误的答案。得到一个未经“验证的错误”知道怎么解决吗?
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
    }
});