首页 > 解决方案 > React Native socket.io客户端连接成功,但两端均未收到发射

问题描述

我正在尝试在 socket-io 服务器和 iOS 应用程序之间进行通信。设备根据两个日志进行连接,但socket.emit()来自客户端或服务器的任何操作都不会触发.on()另一端的相应事件。这是产生此问题的最小示例。

服务器代码:

from aiohttp import web
import socketio

sio = socketio.AsyncServer()
app = web.Application()
sio.attach(app)

@sio.on('connect', namespace='/mp')
async def connect(sid, environ):
    print("connect ", sid)

@sio.on('chat message', namespace='/mp')
async def message(sid, data):
    print("message ", data)

@sio.on('disconnect', namespace='/mp')
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    web.run_app(app)

客户端代码(React Native 应用程序)

window.navigator.userAgent = 'ReactNative';
import React from "react"
import openSocket from "socket.io-client"
import { StyleSheet, Text, View, FlatList } from "react-native"
console.ignoredYellowBox = ["Remote debugger"]
import { YellowBox } from "react-native"
YellowBox.ignoreWarnings([
    "Unrecognized WebSocket connection option(s) `agent`, `perMessageDeflate`, `pfx`, `key`, `passphrase`, `cert`, `ca`, `ciphers`, `rejectUnauthorized`. Did you mean to put these under `headers`?"
])
var app = null
var socket = openSocket("http://localhost:8080/mp", {
            jsonp: false,
            reconnection: true,
            reconnectionDelay: 500,
            reconnectionAttempts: Infinity,
            transports: ["websocket"]
        })

export default class App extends React.Component {
    constructor(props) {
        super(props)
        app = this

        socket.on("connect", function() {
            console.log("connected")
            socket.emit("message", "test")
        })

    }

    render() {
        app = this
        return (
            <View style={styles.container}>
                <Text>Open up App.js to start working on your app!</Text>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#fff",
        marginLeft:20,
        marginTop: 40,
    }
})

标签: socketsreact-nativesocket.io

解决方案


原来问题是我正在向message服务器发送事件,但服务器正在侦听事件chat message(我混淆了事件名称及其功能)。即使那样,服务器到客户端的通信仍然无法正常工作,所以我想它更多的是调试:P


推荐阅读