-
haXe, Node.js and Remotes
haxe remoting is a useful technique for transferring serialized objects between haxe platforms. Remoting can be used asynchronously over http.
Node.js although not an officially supported platform of haXe is available via these type signatures.
http://github.com/cloudshift/hx-node
That is, haxe can generate javascript from statically typed haxe code.
Node.js can be a great haxe remoting target with some tweaks. It needs to process http posts, decode the serialized object pass it to a function, gather the output and pass a serialized object back.
The main issue is haxe remoting on the backend assumes a blocking server, that is, the processing remote function must return a value, not callback a value. This doesn’t work well in a single threaded non-blocking server such as node. Thus the standard haxe.remote.HttpConnection.processRequest function needs altered as does haxe.remote.Context.
I’ve made the required tweaks here in this project which also provides an http server.
http://github.com/cloudshift/Http
You can create a haxe remote like this
var http = Http.server(“localhost”,8082,{ server: “MyServer 0.5”,root:”www” });
var remote = Http.remote(http,”/my/remote”);
remote.addObject(“MyRemote”,new MyRemotes());where MyRemotes looks like this
class MyRemotes {
public function new() {}public function foo(x:Int,y:Int,cb:Int->Void) {
cb(x+y);
}}Notice we’re calling back rather than returning from foo. And on the client
var URL = “http://localhost:8082/my/remote”;
var cnx = haxe.remoting.HttpAsyncConnection.urlConnect(URL);
cnx.setErrorHandler( function(err) trace(“Error : “+Std.string(err)) );
var proxy = new MyRem(cnx.MyRemote);
cnx.MyRemote.foo.call([5,2],function(v) { trace(“value = “+v); });This is precisely the normal haXe client code for an async remoting call. How about remoting proxies?
By creating a proxy class you may have typed calls on the client
import MyRemotes;
class MyRem extends haxe.remoting.AsyncProxy<MyRemotes> { }The haXe code generator creates a typed proxy class automagically for you, allowing the following
var proxy = new MyRem(cnx.MyRemote);
proxy.foo(5,4,function(v) { trace(“value=”+v); });However the default haxe js generator wants to try and serialize the final function which is incorrect, so use the custom generator provided like this
-js www/client.js-cp src
-cp ../http
—macro exclude(“MyRemotes”)
—macro cloudshift.http.JSGenerator.use()
-main TestClient