繁体   English   中英

将 React Native Socket.io-client 与 Python 服务器连接起来

[英]Connecting React Native Socket.io-client with Python Server

我正在尝试将 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:我试图捕捉连接到服务器时产生的任何错误,并简单地创建了套接字 object,没有连接到服务器,没有产生错误。 这怎么可能。 镜像中没有连接,创建了 object

  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,第三天

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM