4

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this. In my case switching out localhost with my local ip was all I needed to do, no need to mess with connectionConfig for me.
I still wonder why my this.socket.on('connect',... is not being called.
0
first get thiss package > socket.io-client
then 
import io from "socket.io-client";
then 
const socket = 
io.connect("http://192.168.64.194:3000");

Note: 192.168.64.194 this is called IP, it is changed based on your internet net work! Put your own IP into here. Where/how do you find IP? It is easy, every time when you run your app, you see this in you terminal:

*Metro waiting on exp://192.168.64.194:xxxx,*

that is it. The 3000 is the port, it should be the same in the frontend and backend.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.