jsSO - Flash Shared Objects in Javascript

Why?

Lately I was discussing about programming a flash-based multiuser game using sharedObjects.
I’m not so fond of Flash so I thought: Flash can communicate with Javascript. So why not implement the game in Javascript and do only the multiplayer-communication in flash?
I created jsSO to allow the clients to push data to the server and notify other clients immediately about changes.
So this library allows programming of realtime games, chats etc.

How?

There is no easy way to get a notification in Javascript on the client about changes on the server.
So the solution is to use Flash and let it handle the update notifications.
You have to install the Flash server from Adobe or se the free java alternative: Red5 as in the example below.

The data-transfer and the connection to the server are maintained by a simple embedded Flashmovie in your page.
The communication with other clients runs through the local Flashmovie and the Red5-Server.

The data-flow between two clients looks like this:


Image created by rhio.kim

Dependencies

  • Javascript-Libraries: jquery + swfobject
  • Flash-Remoting-Server: red5 or similar

Demos

I’m currently working on improving jsSO, so if the demos are not working please come back later, or try them on your own red5-server! :)
Update 2010: I have no Red5 Server running anymore, so the demos won’t work.
Open 2 Windows with the same demo and see how fast e.g. drawing in one window shows up on the other window!
Simple Button Example
Draw
Chat
Call Server Side Functions

Downoad / Repository

Releases

2009-04-15: Version 0.2
* Allow calling functions on the server
* Event Handlers: e.g. detect connect/disconnect to rtmp-server
2009-02-24: Version 0.1 (Inital release)

Source

SVN at code.google.com
including all JavaScript examples and a Java red5-demo

Usage

Include the Javascripts

<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jsSO.js"></script>

Example Shared Object Usage

// Connect to to a shared object Handler (SOSample) on the Red5-Server and
// use the objectName "draw". The objectName is identical to a namespace
// for your data or a chat-room.
// SOSample is the simplest shared object example of the Red5-server
jsSO.connect('rtmp://localhost/SOSample', 'draw');
 
// On button click set someVar in the shared object
$(':button').live('click', function(){
    jsSO.set('someVar', 'value');
});
 
// Listen to changes on the shared object
// event = A jquery event object
// updates = If a var is updated it is set in the updates-object.
//           See code below for usage
// data = All data in the object
jsSO.onSync(function(event, updates, data) {
    if (updates.someVar) {
        // someVar was updated
        console.log(data.someVar);
    }
});

Other useful functions

// get the current data of the shared object
var data = jsSO.getData();
 
// get the last updates on the shared object
var updates = jsSO.getUpdates();

Event Handlers

// events from jsSO:
// connection: onConnect, onConnectError, onDisconnect
// shared object sync: onSync
// one of these fires for each server-call: onCallResponse, onCallError
 
jsSO.onConnectError(function(event, code){
    // couldn't connect
});
jsSO.onDisconnect(function(event, code){
    // server disconnected me
});
jsSO.onCallError(function(event, error){
    // global error handler for all calls
});

Calling Server-Side Methods

jsSO allows now calling Server-Side Methods.

  1. connect() to the server, you only have to provide a rtmp-url if you do not neeed a shared-object
  2. jsSO calls the server-function getServiceList and creates a client-side jsSO.service object with all available methods.
  3. Calling a server-method is now as easy as: jsSO.service.helloWorld()
  4. To get results from the server i’ve borrowed the mochikit/dojo service syntax:
    call addCallback() on the return value of the method to get the server-response or
    call addErrback() to get server errors.

Live Demo

Example

jsSO.connect('rtmp://pro-web.at/firstapp', {debug: true});
 
jsSO.onConnect(function(){
 
    // call function
    jsSO.service.add(2, 4).addCallback(function(ret){
        console.log(ret); // 6
    });
    // call alternative
    jsSO.call('add', 2, 4).addCallback(function(ret){
        console.log(ret); // 6
    });
 
    // call unknown function
    jsSO.call('unknown').addCallback(function(ret){
        // we don't get here
        console.log('OK');
    }).addErrback(function(error){
        // error object is printed
        console.log(error);
 
        // error.application = "org.red5.server.service.MethodNotFoundException"
        // error.code = "NetConnection.Call.Failed"
        // error.description = "Method unknown without arguments not found"
        // error.level = "error"
    });
 
    // call a function, which throws an exception
    jsSO.service.throwException().addCallback(function(ret){
        // we don't get here, because the server java code throws an exception
        console.log('OK');
    }).addErrback(function(error){
        // error object is printed
        console.log(error);
 
        // error.application = "example.remoteapp.TestException" (the exception class)
        // error.code = "NetConnection.Call.Failed"
        // error.description = "some error occured" (the exception description)
        // error.level = "error"
    });
});

Server-Side: read all Services with the annotation @Service

package jsso;
public class Application extends org.red5.server.adapter.ApplicationAdapter
{
    /**
     * Allows the javascript-client to retrieve a list of available methods
     */
    @Service
    public ArrayList<String> getServiceList() {
        ArrayList<String> serviceMethods = new ArrayList<String>();
        Method[] methods = this.getClass().getMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(Service.class)) {
                serviceMethods.add(method.getName());
            }
        }
        return serviceMethods;
    }
}

Server-Side: the implemented Methods

public class Application extends jsso.Application
{
    @Service
    public int add(int a, int b) {
        return a+b;
    }
 
    @Service
    public Object throwException() throws Exception {
        throw new TestException("some error occured");
    }
}

Future Improvements

  • Allow multiple connections with different objectNames to the Server
  • Automatic reconnect to sharedObject on connection loss
  • Fallback in case flashplugin is not present

23 Responses to “jsSO - Flash Shared Objects in Javascript”

  1. guu Says:

    Hi, in Red5 server version 0.8 RC2 the SOSample doesn’t came pre-installed, so you have to start the server, go to the default home page (http://localhost:5080/), then select install demos and select the SOSample demo to make jsSO work properly. It took me like two hours to figure out that.

    Once I did that, everything work right. Thanks, great work.

  2. guu Says:

    Hi again. I’m not in AS3, so I want to play around with connector.as, but can’t recompile it with Flex 3 SDK.

    Could you explain how do you do it? Do you use the mxlmc.exe command?

  3. Daniel Prieler Says:

    hi guu,

    currently i’m switching from as2 to an mxml/as3 solution. i’m developing under flexDeveloper, but it should compile by hand under mxmlc also. i will create a repository on google-code with the newest version. unfortunately the name jsso is already taken so i have to come up with a new name :>

    also thanks for your comments

    daniel.

  4. guu Says:

    What about the name jsRTMP as project name? is longer, but seems to be free too

  5. don Says:

    rad!

  6. Adobe — наш верный друг » jsSO – шаровые flash-объекты и общение клиентов меж собой — блог о air, flash, flex и других технологиях Adobe Says:

    [...] jsSO – это js-библиотека, которая позволяет клиентам при помощи JS взаимодействовать друг с другом через внедрённую флэшку, конектющуюся к rtmp-flash-серверу. Примерно так: Javascript/jsSO <-> Flashmovie <-> Red5-Server <-> Flashmovie <-> Javascript/jsSO. [...]

  7. Adex Says:

    Hello , I have a problem , becauce the SOSample is working (the ball demo is working whit RED5) but your examples aren`t working ? Please help!!!

  8. Flash cookies — Blackhat SEO Says:

    [...] example, plus source code, ofsetting Flash cookies via javascript. Also of interest: SWFObject and jsSO. Posted on Saturday, August 29th, 2009 at 1:10 pm under Asides. You can skip to the end and [...]

  9. links for 2009-10-12 « toonz Says:

    [...] jsSO « pro-web.at (tags: flash jquery library as3) [...]

  10. Flash cookies | I Can Has Rankings? Says:

    [...] A useful example, plus source code, of setting Flash cookies via javascript. Also of interest: SWFObject and jsSO. [...]

  11. Barry Says:

    This looks like a cool project and is exactly what I need. However, it is licensed under GPL v3 which means it can’t be used in anything that isn’t also GPL v3. Any chance you could change the license to the MIT License, or dual license it MIT and GPL? Otherwise, I have to build this from scratch myself.

  12. Romelia Nienaber Says:

    The Zune concentrates on being a Portable Media Player. Not a web browser. Not a game machine. Maybe in the future it’ll do even better in those areas, but for now it’s a fantastic way to organize and listen to your music and videos, and is without peer in that regard. The iPod’s strengths are its web browsing and apps. If those sound more compelling, perhaps it is your best choice.

  13. Can Crusher Says:

    ;,” I am really thankful to this topic because it really gives great information `;’

  14. wholesale la martina Says:

    Hi there, I simply hopped over on your site by means of StumbleUpon. No longer something I’d most often learn, however I favored your emotions none the less. Thank you for making something value reading.

  15. Rock Says:

    Well, It can’t be used in anything that isn’t also GPL v3. Any chance you could change the license to the MIT License, or dual license it MIT and GPL? Otherwise, I have to build this from scratch myself, Thanks for the share….

    custom printing

  16. Kacey Schwulst Says:

    Nice post. I learn one thing more challenging on different blogs everyday. It’s going to always be stimulating to learn content from different writers and apply a bit of one thing from their store. I’d desire to make use of some with the content material on my weblog whether or not you don’t mind. Natually I’ll give you a hyperlink on your web blog. Thanks for sharing.

  17. Hfamgbqv Says:

    military tattoos pictures,

  18. Vanessa A. Price Says:

    Best of the blogs that looked today, the most interesting and intresujące articles, certainly recommend to others.

  19. salary Says:

    I used to be more than happy to search out this net-site.I wanted to thanks to your time for this excellent learn!! I undoubtedly enjoying each little bit of it and I have you bookmarked to take a look at new stuff you blog post.

  20. Medical Alert Systems Reviews Says:

    I think this is among the most vital information for me. And i am glad reading your article. But want to remark on few general things, The web site style is ideal, the articles is really great : D. Good job, cheers

  21. Niche Finder Review Says:

    Undeniably believe that which you stated. Your favorite reason seemed to be on the web the simplest thing to be aware of. I say to you, I certainly get annoyed while people think about worries that they plainly do not know about. You managed to hit the nail upon the top and also defined out the whole thing without having side effect , people can take a signal. Will probably be back to get more. Thanks

  22. what stores carry ugg boots Says:

    Hi there! I simply want to give an enormous thumbs up for the great data you have here on this post. I shall be coming again to your weblog for more soon.

  23. mobile mass money review Says:

    Hello, i think that i saw you visited my website thus i came to “return the favor”.I’m trying to find things to enhance my website!I suppose its ok to use some of your ideas!!