Cocos2d: compile JS code, with remote server communication, to native platforms - cocos2d-js

Setup:
cocos2d-x-3.7
created project with: "cocos new MyGame -l js -p org.cocos2d.mygame"
i will write the code in Javascript
Question:
What is the way to do server communication from javascript code(e.g. AJAX).
It should work also, after compiling to native plattforms
e.g. "cocos run -p mac"
Maybe with:
cc.loader.loadJson("http://REMOTE_URL_HERE", function(error, data){ cc.log(data);});
But I get:
"Get data from file http://REMOTE_URL_HERE failed"
Any Ideas?
Thanks
I found:
cocos2d-js: How to load a JSON file
but this is only for loading local files

found a solution:
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function() {
//xhr.statusText;
//xhr.responseText
};
xhr.send();

Related

Connection refused when launching Electron app generated with electron-packager/ electron-builder

I have a React Electron app with Webpack and try to build it into an executable.
I used the CLI commands of electron-packager and electron-builder which ran without errors.
But when I run the exe I get a blank screen and from terminal the error message:
(node:8172) electron: Failed to load URL: http://localhost:3000/main_window with error: ERR_CONNECTION_REFUSED
(Use mixmatch --trace-warnings ... to show where the warning was created)
Running with the option doesn't give any additional information.
Searching the source code for localhost leads to index.js in the webpack directory:
var createWindow = function () {
var preload = path_1.default.join(__dirname, '../renderer/main_window', "preload.js");
exports.mainWindow = new electron_1.BrowserWindow({
// show: false,
webPreferences: {
enableRemoteModule: false,
// nodeIntegration: false, // is default value after Electron v5
preload: preload // use a preload script
}
});
exports.mainWindow.loadURL('http://localhost:3000/main_window');
exports.mainWindow.maximize();
exports.mainWindow.webContents.openDevTools();
};
So I guess a server is being started, which probably is the same for every app, but the app is not allowed to access localhost.
So why does it seem to work easily for everyone else but not for me?
Once the build is created, you need to loadURL from build/index.html.
Replace your code of export.mainWindow.loadURL with this
e.g.
const isDev = require('electron-is-dev');
exports.mainWindow.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, '../build/index.html')}`
);

Deploy Angular 2 app to Heroku

In the past I always bundled my Angular 1 and Rails apps together and typically used heroku, which has worked great for me. Now that I'm over to Angular 2 I want to separate out my Angular and Rails code. I've created a very basic Angular 2 app via the Angular-Cli, but I haven't been able to figure out how to deploy it to Heroku. I'm not using expressjs or anything like that. Anyone figure it out yet?
Ok I came up with a solution. I had to add a very basic PHP backend, but it's pretty harmless. Below is my process.
First setup a heroku app and Angular 2 app.
Create your heroku app
Set the heroku buildpack to heroku/php
heroku buildpacks:set heroku/php --app heroku-app-name
Create a project via Angular-Cli
Add a index.php file to /scr with the below snippet
<?php include_once("index.html"); ?>
Add a Procfile to /scr with the below snippet
web: vendor/bin/heroku-php-apache2
Added /deploy to the .gitignore
Now I used a npm package to push a tarballs to heroku
Here's a simple package to upload the tarball, https://www.npmjs.com/package/heroku-deploy-tarball
npm i heroku-deploy-tarball --save
I'm also using tar.gz to create the tarball
npm i tar.gz --save
Then I created the deploy.js file at the root of my projecdt with the following code. I first run the buildCommand specified and then move the index.php and Profile to the dist folder. I then tarball the entire dist folder and it gets uploaded to heroku.
var deploy = require('heroku-deploy-tarball');
var targz = require('tar.gz');
var exec = require('child_process').exec;
var requestedTarget = process.argv[2];
if (!requestedTarget) {
console.log('You must specify a deploy target');
return;
}
var targets = {
production: {
app: 'heroku-app-name',
tarball: 'deploy/build.tar.gz',
buildCommand: 'ng build --prod'
}
}
var moveCompressFiles = function (callback) {
exec('cp ./src/index.php ./dist/index.php',
function(err) {
if(err)
console.log(err);
console.log('index.php was copied.');
});
exec('cp ./src/Procfile ./dist/Procfile',
function(err) {
if(err)
console.log(err);
console.log('Procfile was copied.');
});
new targz().compress('./dist', './deploy/build.tar.gz',
function(err){
if(err)
console.log(err);
else
callback();
console.log('The compression has ended!');
});
};
console.log('Starting ' + targets[requestedTarget].buildCommand);
exec(targets[requestedTarget].buildCommand, {maxBuffer: 1024 * 500}, function(error) {
if (!error) {
console.log(targets[requestedTarget].buildCommand + ' successful!');
moveCompressFiles(function () {
deploy(targets[requestedTarget]);
});
} else {
console.log(targets[requestedTarget].buildCommand + ' failed.', error);
}
});
Now just run node deploy production and it should deploy to heroku.
Edit
Just got word from heroku that they are working on an experimental buildpack that would allow for static sites like this. Here is the link to the build pack.

React Native Socket.io How to Connect to Local Node Server from Device

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.
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.
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..!

How to find path to the package directory when the script is running with `pub run` command

I am writing a package that loads additional data from the lib directory and would like to provide an easy way to load this data with something like this:
const dataPath = 'mypackage/data/data.json';
initializeMyLibrary(dataPath).then((_) {
// library is ready
});
I've made two separate libraries browser.dart and standalone.dart, similar to how it is done in the Intl package.
It is quite easy to load this data from the "browser" environment, but when it comes to the "standalone" environment, it is not so easy, because of the pub run command.
When the script is running with simple $ dart myscript.dart, I can find a package path using dart:io.Platform Platform.script and Platform.packageRoot properties.
But when the script is running with $ pub run tool/mytool, the correct way to load data should be:
detect that the script is running from the pub run command
find the pub server host
load data from this server, because there could be pub transformers and we can't load data directly from the file system.
And even if I want to load data directly from the file system, when the script is running with pub run, Platform.script returns /mytool path.
So, the question is there any way to find that the script is running from pub run and how to find server host for the pub server?
I am not sure that this is the right way, but when I am running script with pub run, Package.script actually returns http://localhost:<port>/myscript.dart. So, when the scheme is http, I can download using http client, and when it is a file, load from the file system.
Something like this:
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart' as ospath;
Future<List<int>> loadAsBytes(String path) {
final script = Platform.script;
final scheme = Platform.script.scheme;
if (scheme.startsWith('http')) {
return new HttpClient().getUrl(
new Uri(
scheme: script.scheme,
host: script.host,
port: script.port,
path: 'packages/' + path)).then((req) {
return req.close();
}).then((response) {
return response.fold(
new BytesBuilder(),
(b, d) => b..add(d)).then((builder) {
return builder.takeBytes();
});
});
} else if (scheme == 'file') {
return new File(
ospath.join(ospath.dirname(script.path), 'packages', path)).readAsBytes();
}
throw new Exception('...');
}

Dart: How to Implement and install a simple HTTP server

I have been able to run the dart-by-example http-server Hello web server.
The websocket uses port 9223 and the http server uses 8080.
After I do a build I do not find the server side code in build/bin.
What do I do next to install everything so that I could try run ws_server.dart and connect from my browser?
My Editor organization:
Server
packages
bin
packages
fireimager_server.dart (server side websocket handling code)
build
bin
web
lib
communication.dart (common code)
web
index.html
main.css
main.dart
WebsocketClient.dart (client websocket code)
If you follow the package layout convention, you server.dart should be in $PROJECT/bin and your web stuff in $PROJECT/web.
By running pub build you should get a new directory $PROJECT/build/web. Now you can use the following server.dart code to expose this build directory :
library simple_http_server;
import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;
void main() {
final MY_HTTP_ROOT_PATH = Platform.script.resolve('../build/web').toFilePath();
final virDir = new VirtualDirectory(MY_HTTP_ROOT_PATH)
..allowDirectoryListing = true;
HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
server.listen((request) {
virDir.serveRequest(request);
});
});
}

Resources