im trying to connect to socketio with expo and reacti-native for ios(connection through expo app tunnel connection) and android with emulator, when i tried to connect with these the socket won't connect but if i open the expo app in broswer socket connection works but on mobile emulators not.. what can i do? code for client
import { StatusBar } from 'expo-status-bar';
import React, { useEffect, useState } from 'react';
const io = require('socket.io-client');
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import Navigation from './navigation';
import { Provider } from 'react-redux';
import { store } from './redux/store'
export default function App() {
const isLoadingComplete = useCachedResources();
const [data, setData] = useState(null)
useEffect(() => {
const socket = io('http://localhost:5000', {
});
socket.on("ping", (data: any) => {
setData(data)
})
}, [])
console.log(data)
if (!isLoadingComplete) {
return null;
} else {
return (
<Provider store={store}>
<SafeAreaProvider>
<StatusBar style="dark" />
<Navigation />
</SafeAreaProvider>
</Provider>
);
}
}
code for server
require("dotenv").config();
const express = require("express");
const http = require("http");
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 5000;
const io = socketIO(server);
io.on('connection', socket => {
console.log('client connected on websocket');
setInterval(() => {
io.emit('ping', { data: (new Date()) / 1 });
}, 1000);
});
server.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`));
Make sure you are connecting with the right versions in each part, client and server. Review https://socket.io/docs/v3/client-installation/index.html to make sure you have the right versions. I went through the source code and make sure mine was setup right and couldn't figure out why it wouldn't run.
I had a 4.0.1 of the socket.io-client installed in my react native expo app but only had 2.1.1 socket.io installed in the server. Once I upgraded to 4 on the server everything worked.
Also on the client side change
const socket = io('http://localhost:5000', {});
to
const socket = io('http://localhost:5000', {transports: ['websocket']});