我是 React Native 的新手,但对 React 非常熟悉。正如我在文档中看到的那样,作为初学者,我希望在云服务器和使用 websockets 的 react-native 之间建立连接。不幸的是,没有像样的例子可以帮助我。这就是我到目前为止所拥有的一切:
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 客户端进行了测试,一切都很顺利……看看我如何才能修复这个问题或一些我可以弄清楚的示例源。
原文由 Razvan Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
更改代码
到
它应该工作。
这是我要测试的代码,基于您的代码和 RN 0.45(以及由 create-react-native-app 生成的项目),连接到公共 websocket 服务器
wss://echo.websocket.org/
,在我的 android 上它工作正常,我按下按钮后可以看到 websocket 服务器的回显消息。