Reputation: 407
I'm trying to build a real-time multi-player game using React Native, basically I want to make one of the phones as my server and the other ones as clients which are connected to the server. this is my Express server:
server.js
let app = require('express')();
let port = 3000;
let server = require('http').createServer(app)
let io = require ('socket.io')(server)
module.exports = startServer = () => {
io.on("connection", () => {
console.log("someone has connected");
})
server.listen(port, () => {console.log("server is running at " + port)})
}
App.js
import React, { Fragment } from "react";
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
TextInput,
Text,
StatusBar
} from "react-native";
let startServer = require('./server')
class App extends React.Component {
componentDidMount() {
startServer();
}
render() {
return (
<View style={{justifyContent: 'center', alignContent: 'center', flex: 1}}>
<TextInput style={{borderBottomWidth: 1}}/>
</View>
);
}
}
const styles = StyleSheet.create({});
export default App;
I use startServer
in componentDidMount
to start the server (just like how we do it with node server.js
).
client.js
let io = require('socket.io-client');
let port = 3000
start = () => {
socket = io(someIP + ":" + port);
}
So there are a few questions:
1- Is my general approach to implementing this rational and suitable?
2- React Native is unable to resolve module http
, what's the alternative for creating a server in React Native?
3- What's the ip of the server that I must connect to in client.js? (should all devices be necessarily connected to the same internet network?)
Upvotes: 2
Views: 1801
Reputation: 89
Personally don't think it's a good design choice to let a phone host a server for a game. Incredible amount of latency and lag will be introduced as a result of unstable network. If you are on a network, why not just call to an external server with socketio.
This is pretty niche. A little search I found "React Native does not implement node apis, this is why you cannot use the http module." from janicduplessis on react-natives github page. I did find a package react-native-http-bridge, but I think it doesn't support socketio. The funny part is I have looked into running a server on a phone before, and there are some native packages that do this for you (I think it was using WebSocket to host a POS system on a android pad). But the whole thing feels kind of like a hack.
I'd imagine 10.0.2.2:port for android. Idk about IOS. and you have to connect other people's phones to your local IP address like 192.168.1.06:port. It should say in your phone's network settings. Sometimes you have to connect to your own phone using that local IP address too. Not really sure unless I try.
Upvotes: 1