javascript - 将 React Native Socket.io-client 与 Python 服务器连接起来
问题描述
我正在尝试将 React Native 客户端连接到开放的 Python 服务器
问题是我阅读了几个关于如何与 socket.io-client API 建立连接的解决方案,但没有解决它。
它只是不连接。我将发布服务器和客户端,并且我已经更改了几次。
编辑* 1:服务器端工作,我测试它,使用 socket.io 和 python 套接字。但是作为 React 的客户端不起作用
import React,{useState, useEffect} from 'react';
import { StyleSheet, Text, View, Pressable, Button } from 'react-native';
import socketIO from "socket.io-client";
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
string:"null",
chatMessage:"null",
chatMessages:[]
}
}
componentDidMount() {
this.socket = socketIO('192.168.0.107:15156')
this.socket.connect();
this.socket.on('connect', () => {
console.log('connected to socket server');
});
}
submitChatMessage(message) {
console.log(this.socket)
this.socket.emit('chat message', message);
this.setState({chatMessage: ''});
}
render() {
return (
<View style={{flex: 1,backgroundColor:'#000000', alignItems:'center', justifyContent:'center'}}>
<Button title="Start" onPress={()=>{this.submitChatMessage('connected')}}></Button>
</View>
);
}
}
服务器
import socket
host = "192.168.0.107"
port = 15156
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (host, port)
tcp.bind(orig)
tcp.listen(1)
while True:
con, cliente = tcp.accept()
print ('Connected', cliente)
while True:
msg = con.recv(1024)
if not msg: break
print (cliente, msg)
print ('exiting', cliente)
con.close()
编辑*2:我试图捕捉连接到服务器时产生的任何错误,并且只是创建了套接字对象,没有连接到服务器,没有产生错误。这怎么可能。图像中没有连接,对象被创建
componentDidMount() {
this.connectSocket()
}
connectSocket() {
try {
console.log("Connecting to the server...")
this.socket = io('http://192.168.0.107:15156',{autoConnect:false})
this.socket.connect()
console.log("Sucess");
}
catch (err){
console.log(err)
}
}
编辑*3 我在使用它时能够检测到错误,
this.socket.on("connect_error", (err) => {
console.log(err)
})
// [Error: xhr poll error] //循环
关键是,最好不要找到它。有前进的方向吗?
解决方案
我只是忘记连接网络上的android,第三天
推荐阅读
- python - 以 csv 格式保存数据帧后获取双引号
- javascript - 使用回调返回组件
- json - 如何在jmeter中使用JRS223预处理器修改json
- javascript - 从另一个组件重置 BehaviorSubject
- javascript - 如何为 renderToNodeStream (React SSR) 块收集关键 css
- javascript - 如何将 __ob__: Observer 转换为数组?Vue
- java - 目标c中的类和扩展接口
- android - 在 AppCompatActivity 中以编程方式启用后退按钮
- sql-server - SQL Server 2014 中的用户帐户与 IP 地址的映射
- reactjs - Reactjs with 3x.antd --- 警告:`getFieldDecorator`会覆盖`value`,所以请不要直接设置`value`,使用`setFieldsValue`来设置