【问题标题】:Cannot send a message between client and server using socket.io in react-native无法在 react-native 中使用 socket.io 在客户端和服务器之间发送消息
【发布时间】:2018-09-05 02:40:44
【问题描述】:

我是 react-native 的新手,并试图在我的应用程序中实现 socket.io。我想我做的一切都是正确的,但仍然无法正常工作。

这是我的代码 sn-ps :

App.js

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
// window.navigator.userAgent = 'react-native';
import io from 'socket.io-client/dist/socket.io'

export default class App extends React.Component {
    state = {
        name: 'Hello World!'
    };

    constructor(props) {
        super(props);
        this.socket = io('http://192.168.1.24:19001'/*, {transports: ['websocket']}*/);
        this.socket.on('connect', () => {
            console.log('connected');
        });
        this.socket.on('update', () => {
            console.log('yay');
            this.setState({name: 'Done did it!'})
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <Text>{this.state.name}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
});

我创建了一个文件夹“服务器”,其中包含以下代码:

服务器/app.js

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen('19001', '192.168.1.24');

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    console.log(socket.id);
    socket.on('update', () => {
        console.log('update');
        socket.emit('update')
    });
});

我制作了一个与应用程序交互的 html 页面。

服务器/index.html

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen('19001', '192.168.1.24');

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {
    console.log(socket.id);
    socket.on('update', () => {
        console.log('update');
        socket.emit('update')
    });
});

我也尝试使用 localhost 而不是 IP 地址。那也没用。

请帮忙!

【问题讨论】:

  • 你能把正确的代码放在这里吗?

标签: reactjs react-native


【解决方案1】:
  1. 你为什么使用'socket.io-client/dist/socket.io'?我认为socket.io的客户端只是'socket.io-client'
  2. 建议不要在构造函数中调用 this.setState,即使它在回调函数中也是如此。您可以在屏幕尚未渲染时更新状态,它会引发错误。尝试在 componentDidMount 中移动你的监听器。
  3. 您确定连接完成了吗?!如果是,请尝试将您的侦听器移动到“连接”事件回调中的“更新”事件。
  4. 您的服务器正在侦听 19001 端口。我认为它也是 react native packager 的默认端口。你的服务器启动了吗?如果您没有 root 访问权限,您是否尝试过其他端口,例如 80 其他 8080。

【讨论】:

  • @mcssym我做了你说的一切,但它不起作用,但当我点击按钮时日志工作
  • @Gha 我无法帮助你,因为我没有看到你的代码。也许你有另一件事要做!
  • @Gha 所以我看不出可能是什么问题。对于这个案例,我已经列出了我知道的所有解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-16
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
相关资源
最近更新 更多