把 Node.js 服務器直接跑在手機上,聽起來頗具極客色彩。借助 jxcore 與 Cordova 的組合,這件事真的能實現。下面把整個流程拆解成幾個步驟。
一、為在 iOS 上運行而編譯 jxcore
先把源碼拉下來:
$ mkdir ~/jxcore
$ cd ~/jxcore
$ git clone https://github.com/jxcore/jxcore.git
接著執行 iOS 編譯腳本:
$ cd ~/jxcore/jxcore
$ ./build_scripts/ios-compile.sh
如果遇到 import which 提示 module not found,可以通過下面的命令安裝 Python 的 which 模塊:
sudo easy_install tools/which-1.1.0-py2.7.egg
若遇到其他問題,可以查閱 jxcore 關於 iOS 編譯前提條件的文檔:https://github.com/jxcore/jxcore/blob/master/doc/HOW_TO_COMPILE.md
* GCC 4.2 or newer (for SpiderMonkey builds 4.7+)
* Python 2.6 or 2.7
* GNU Make 3.81 or newer
* libexecinfo (FreeBSD and OpenBSD only)
* for SpiderMonkey : 'which' python module (sudo easy_install tools/which-1.1.0-py2.7.egg)
二、在 Mac 上安裝 jxcore
$ ./configure
$ sudo make install
三、創建 Cordova 程序(若尚未安裝 Cordova,需先自行安裝)
$ cordova create hello com.example.hello HelloWorld
$ cd hello
四、下載並安裝 jxcore-cordova 插件
$ git clone https://github.com/jxcore/jxcore-cordova
使用 jxcore-cordova 提供的模板 index.html:
$ cp ./jxcore-cordova/sample/www/index.html ./www/
把第一步中為 iOS 編譯好的 jxcore 包拷貝進來:
$ cp -r ~/jxcore/jxcore/out_ios/ios/bin jxcore-cordova/io.jxcore.node/
五、添加 Cordova 的 iOS 平台
$ cordova platforms add ios
$ cordova plugin add jxcore-cordova/io.jxcore.node/
$ cordova build
$ cordova run ios
如果 build 時報出 "C does not support default arguments" 的錯誤,一般只要去掉默認參數值即可解決。也就是把:
JXCORE_EXTERN(void)
JX_SetString(JXValue *value, const char *val, const int32_t length = 0);
改為:
JXCORE_EXTERN(void)
JX_SetString(JXValue *value, const char *val, const int32_t length);
然後重新 build 就可以了。
六、此時應該能看到 Cordova 的運行界面。
七、在 Resources/jxcore_app/app.js 中添加 Node.js 服務器
在 app.js 末尾追加以下代碼,即可啟動一個簡單的 HTTP 服務,並在控制台打印出 iPhone 的 IP:
function getIP() {
var os = require('os');
var nets = os.networkInterfaces();
console.log(nets);
for ( var a in nets) {
var ifaces = nets[a];
for ( var o in ifaces) {
if (ifaces[o].family == "IPv4" && !ifaces[o].internal) { return ifaces[o].address; }
}
}
return null;
}
var ip = getIP();
if (!ip) {
console.error("You should connect to a network!");
return;
}
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
var cur_client = "";
if(req.connection && req.connection.remoteAddress) {
console.log(req.connection.remoteAddress);
cur_client = req.connection.remoteAddress;
} else if(req.headers) {
console.log("request header X-Forwarded-For");
console.log(req.headers['X-Forwarded-For']);
cur_client = req.headers['X-Forwarded-For'];
}
cordova('log').call('client( ' + cur_client + ' ) come');
res.end('Hello '+ cur_client +', I am server on iphone app('+ ip +'). '+Date.now()+'\n');
}).listen(1337, ip);
console.log('Server running at https://' + ip + ':1337/');
運行程序後,在 Xcode 的 log 信息裡就能看到 iPhone 的 IP,接著用任意瀏覽器訪問該地址,即可訪問到手機上的網頁服務了。