Reputation: 937
I'm making a connection when pointing the io.connect()
method towards my localhost
in the iOS simulator, so everything is working there.
But when the connect()
method is pointed towards my machine's LAN IP address I am unable to successfully connect to the server neither in the simulator or on the device..
I'm pretty stumped on this one right now, any help would be appreciated thanks.
Upvotes: 8
Views: 2198
Reputation: 3317
Simple way -> Connection with Socket.io to Local Node Server:
First Step : you need to install socket.io into your project -
npm install socket.io-client
or
yarn add socket.io-client
App.js file :
import { io } from "socket.io-client";
const socketIOConnectionWithLocalhost = () => {
var socket = io('localhost:3000', { jsonp: false });
console.log('socket: ', socket);
socket.on('connect', () => {
console.log("socket connected...");
})
socket.on("update", () => {
console.log('App.js : socket event recieved:');
});
};
Second Step : create server folder and inside it create two files: app.js and index.html (As per given in below image)
Server/app.js File :
var express = require('express');
var app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('server - app.js - socket.id: ', socket.id);
socket.on('update', (data) => {
console.log('server - app.js - update:', data);
io.emit('update', socket.id)
});
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
server.listen(3000);
index.html file :
<h1>Welcome To Server</h1>
<button>UPDATE</button>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io();
var button = document.querySelector('button');
button.onclick = function(){
console.log('index.html - buttion click...')
socket.emit('update');
}
</script>
Third Step : To start node server using below command:
first go to inside server folder then enter below command -> cd Server
node app.js
Then open any browser and hit localhost url -> http://localhost:3000/
Thanks..!
Upvotes: 0
Reputation: 937
Solved by tunneling localhost:3000
via ngrok and allowing an exception domain.
In your info.plist
you need the following under App Transport Security Settings
On a mac command line run
brew cask install ngrok
ngrok http 3000
Then grab the outputted ngrok.io URL and use it in your io.connect()
call and you should be set.
Upvotes: 4