Socket.io和React Native,不能从手机发出事件?

时间:2018-05-19 07:15:55

标签: javascript node.js react-native socket.io

尝试让socket.io与RN合作。我已经验证连接建立成功,服务器将在客户端连接后获得事件触发器,但这就是全部。

正如您在我的服务器中看到的,我有几个自定义事件。我尝试从React Native代码发出这些事件,但没有触发,我不知道为什么。

我尝试在不同的函数中将RN函数中的emit函数抛出,但我的服务器上没有日志。造成这种情况的原因是什么?

  

我简化了RN代码,以阐明最重要的部分。

基本服务器

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

const PORT_NUM = 3000;

io.on('connect', (socket) => {
    console.log('someone joined!', socket.id);
});

io.on('sendKeys', () => {
    console.log('keys callde!');
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '/index.html'));
});

server.listen(PORT_NUM, () => {
    console.log(`Web Socket Encryption Server Running on *:${PORT_NUM}...`);
});

React Native

import React, { Component } from 'react';
import { View, AsyncStorage } from 'react-native';
import io from 'socket.io-client/dist/socket.io';

class ControlPanel extends Component {

    constructor() {
        super();
        this.state = {

        };

        this.socket = io.connect('http://192.168.0.32:3000', { 
            reconnectionDelay: 1000,
            reconnection: true,
            reconnectionAttempts: 10,
            transports: ['websocket'],
            agent: false,
            upgrade: false,
            rejectUnauthorized: false
        });

        this.socket.on('connect', () => {
          console.log('Mobile Client Socket Connected.');
        });

        this.socket.on('connect_error', (err) => {
          console.error(err);
        });
    }

    componentDidMount() {
          this.generateKeys();
    }

    async generateKeys() {
        this.socket.emit('sendKeys');
    }

    toggleLoader() { 
        this.setState({
            visible: !this.state.visible
        });
    }

    toggleKeysGenerated() {
        this.setState({
            keysGenerated: true
        });
    }

    render() {
     }
}



export default ControlPanel;

0 个答案:

没有答案