Using Socket.io with React Native and not working

2020-07-18 23:24发布

问题:

I'm trying to complete a homework and I need to have websocket for it. I use react native as client and node.js for server. However, even I tried all the solution suggestions on web, I couldn't get it working.

Client

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');
    });
 }

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');
    });
});

Here are the version I am using,

socket.io: 2.1.1

express: 4.16.4

socket.io-client: 2.1.1

expo: 30.0.1

I want to thank you in advance for all your effort.

回答1:

I have found the solution to my problem.

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

I've omitted the connectionConfig from the function call and change the way I write the local host to that.

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

It now works both on android and iOS.