I've built and released very simple AjAX/PHP hybrid apps before in the mobile stores (Google and Apple). Now I'm learning nodejs with socketio. I'm using socketio to do bidirectional communications (server-to-client and client-to-server). I'm able to work with it fairly well on development machine pointing to localhost.
Question is : once the apps are deployed in the mobile stores, how is the server supposed to communicate with the client?
On a development machine it's easy to do since it's local. In development, both the server and apps are on localhost. Server on port 3000 and client-app running on port 8000.
Apps released in stores can't be "pointed" to.
This is my simple app which works well when testing locally on all devices and browsers.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/app.css">
<title>Myapp</title>
</head>
<body id="app" onload="onLoad()"></body>
</html>
<!--SCRIPTS-->
<script src="cordova.js"></script>
//point to localhost server
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script src="js/app.js"></script>
app.js
// Wait for device API libraries to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
//testing socket server
serverTest();
}
//testing socketio server
//see socket.js
//
function serverTest() {
var socket = io.connect('http://localhost:3000');
socket.on('connect', function() {
socket.on('text', function(text) {
//display data on page
document.getElementById('app').innerHTML = text;
});
})
}
socket.js
const path = require('path');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8000",
methods: ["GET", "POST"],
allowedHeaders: ["my-custom-header"],
credentials: true
}
});
/**
*
* use the following code to serve images, CSS files, and JavaScript files in a directory
* https://expressjs.com/en/starter/static-files.html
*
*/
app.use(express.static('js'));
app.use(express.static('css'));
//get
app.get('/', (req, res,next) => {
//...
});
io.on('connection', (socket) => {
//console
console.log('user connected');
//emitting event
socket.emit('text', '<p class="serverTest">server and client are communicating </p>');
});
server.listen(3000, () => {
console.log('listening on *:3000');
});