Friday, May 04, 2012

Russian Roulette Pro on Kongregate!

Free Russian Roulette online game on Kongregate. Play and enjoy!

Friday, April 27, 2012

Tuesday, January 03, 2012

How to create typed AS3 objects from JSON

JSON is very simple and convenient format for communication between Adobe Flash/Flex client and server side. as3corelib library contains class for JSON deserialization from String to Object. It's not good idea to use simple Object because you cannot use Bindable tag in Flex application. Re-factoring will be nightmare for you without typed objects. To solve that problem I created util class to convert Object into typed one. Source code you can see on gist: https://gist.github.com/1556693. I have MessageVO.as class with two attributes: data and type. Type contains information about data. For example, if type equals "user" it means that data will contains object of UserVO class.
public class MessageVO {
    public var type:String;
    public var data:Object;
}
...
[Bindable]
public class UserVO {
    public var id:Number;
    public var nickname:String;
}

To convert object into typed object you should execute the following code:

    var object:* = Converter.convertData(jsonObject, UserVO);

In my project I use dictionary where key is type (string) and value is class. For example:
    var typeToClassMap:Dictionary = new Dictionary;
    ...
    typeToClassMap["user", UserVO];
    typeToClassMap["chatMessage", ChatMessageVO];
    ...
    var jsonObject = JSON.decode(jsonString);
    var object:* = Converter.convertData(jsonObject.data, typeToClassMap[jsonObject.type]);

object variable will contain typed object converted from jsonObject.

How to make release without erts

Erlang OTP has very interesting thing like release. You can upgrade or downgrade your application in real-time. Release contains erts. It means that your release will contain erlang package. If you builds release with ubuntu 10.10/64bit then you cannot use release in archlinux/32bit because of binary incompatibility. Sometimes it's a big problem. I have found way to remove that disadvantages. I modified standard node startup script and created makefile to make package archive. The example you can find in my github project (https://github.com/sinnus/erlang_without_erts_example). Folder release contains bin and etc sub-folders. "bin" sub-folder contains startup scripts (node and nodetool), "etc" sub-folder contains standard  configuration for prod and dev environments (app.config and vm.vargs). Take a look at node shell script. You should replace ERTS_PATH on your real erts path and STARTUP_MODULE on your startup module like https://github.com/sinnus/erlang_without_erts_example/blob/master/src/start_mod.erl. To build package you should run "make package_dev" for dev environment. The package will be in root project folder (example-prod.tar.gz). To run application you should extract package (or use existed target folder) and execute from shell "node console" script. You also can see all available options if you run script without arguments (). There is no problem to run package on other operation system now. I haven't tested upgrade and downgrade release because it was not necessary for my project.

Friday, December 23, 2011

Java, Erlang and Rock'n'Roll

Есть у меня игровой проект под названием Russian Roulette Pro. Адрес Вконтакте http://vkontakte.ru/app2417844, в фейсбуке http://apps.facebook.com/russianroulettepro. Это клиент-серверное приложение. Клиент написан на Adobe Flex, а сервер на Java, используя Netty. Соединение между Adobe Flex и Java сокетное. Но как известно, много кто играет в игры из офиса, где стоят всякие прокси-сервера, которые поддерживают только HTTP протокол. Тут я решил сделать соединение long-polling. Вменяемую реализацию для Netty я не нашел, да и шибко не хотелось, поэтому решил я заюзать модный ныне Erlang для реализации long-polling соединения. Начал искать готовые решения и таки нашел: https://github.com/yrashk/socket.io-erlang. Я вначале обрадовался, что вот она рыба моей мечты, но тестирование показало, что там блокирующая архитектура, в общем решил сделать форк https://github.com/sinnus/socket.io-erlang/tree/dev. Пофиксил некоторые баги, убрал блокирующий процесс. Этот сервер использует протокол Socket.IO (http://socket.io/) версии 0.6. Готовый клиент существовал только для JavaScript, а мне нужен был Adobe Flash клиент. Долго думать не стал и запилил клиент для флеша: https://github.com/sinnus/socket.io-flash. Он поддерживает long-polling и Websocket. Websocket, конечно, работает через сокетные соединения со всеми вытекающими последствиями, как настройка отдачи полиси через сокет. Я в своей рулетке решил воспользоваться только long-polling. Теперь встал вопрос, а как же все это дело прицепить к существующему серверу? Не выбрасывать же существующий код на джаве, не для того он писался, чтобы его выкидывать на помойку! Решение было простое - сделать socket.io-erlang  проксирующим сервером. Клиент подцепляется к 80 порту по Socket.IO протоколу, который слушает erlang. Erlang процесс создает сокетный коннект к Java серверу и затем редиректит сообщения от клиента на Java сервер. В общем, получился такой nginx в мире long-polling - socket. Решение уже работает несколько месяцев и пока проблем не было. Протестировано под всеми браузерами, полет тоже нормальный. Как говорится, Erlang your penis!

Monday, October 24, 2011

How to use JRebel in Eclipse with Jetty plugin

Add VM arguments:
-javaagent:${JRABEL_HOME}/jrebel.jar -Drebel.log=true ${jrebel_args}

Wednesday, August 31, 2011

My own game on facebook!!!

My own game (Russian Roulette Pro) on facebook!!!

Play it!