【问题标题】:Using Socket.io with React Native and not working将 Socket.io 与 React Native 一起使用并且无法正常工作
【发布时间】:2018-10-14 19:21:45
【问题描述】:

我正在尝试完成一项家庭作业,我需要为它安装 websocket。我使用 react native 作为客户端,使用 node.js 作为服务器。但是,即使我尝试了网络上的所有解决方案建议,我也无法正常工作。

客户

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import SocketIO from 'socket.io-client';

const connectionConfig = {
  jsonp: false,
  reconnection: true,
  reconnectionDelay: 100,
  reconnectionAttempts: 100000,
  transports: ['websocket'], // you need to explicitly tell it to use websockets
 };

export default class App extends React.Component {

   constructor() {
    super();
    this.socket = SocketIO('http://localhost:3000',connectionConfig);
    this.socket.on('connect', () => {
         console.log('connected to server');
    });
 }

服务器

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const port = 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);

server.listen(port, () => {
    console.log(port, 'is up');
});

io.on('connection', (socket) => {
    console.log('new user connected');

    socket.on('disconnect', () => {
        console.log('User was disconnected');
    });
});

这是我正在使用的版本,

socket.io:2.1.1

快递:4.16.4

socket.io-client: 2.1.1

世博会:30.0.1

我要提前感谢您的所有努力。

【问题讨论】:

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


    【解决方案1】:

    我找到了解决问题的方法。

    this.socket = SocketIO('http://localhost:3000',connectionConfig);

    我已经从函数调用中省略了 connectionConfig,并将本地主机的写入方式更改为。

    this.socket = SocketIOClient('http://192.168.xxxx:3000');

    它现在可以在 android 和 iOS 上运行。

    【讨论】:

    • 谢谢。在我的情况下,我只需要用我的本地 ip 切换 localhost,不需要为我弄乱 connectionConfig。
    • 我仍然想知道为什么我的this.socket.on('connect',... 没有被调用。
    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 2018-04-12
    • 2020-09-02
    • 1970-01-01
    • 2022-07-04
    • 2018-06-13
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多