AsyncClient Tutorial

mimiyin edited this page Aug 29, 2013 · 4 revisions

A tutorial for how to set up an asynchronous client.

What is an asynchronous client and why would I want/need one?

Async clients are applications that can send and receive messages to the mpe server, but don't need to stay in lock-step with other clients (aka "Rendering clients.) They are useful as controllers for taking in user or data inputs (camera, sound, keyboard, mouse, feeds, sms messages) and sending them to the rendering clients via the mpe server. Async clients are just a variant of the same code behind the rendering clients, so it's simply a matter of changing the settings as defined by an XML file.

Then you make a completely new Processing sketch (or command line java app) with the same TCPClient object you've been using to make your rendering clients:

// A client object
TCPClient client;

In setup(), initialize the Client object. Here, a settings XML file is required. This file tells the client what its local dimensions are, as well as its location within the master dimensions. # indicates a comment and end all lines with a semi-colon (and no spaces!) Here is an example:

	<name>an asynch client</name>  <!-- optional -->
        <!-- Server address. Localhost for testing. -->
        <!-- IMPORTANT!!! Set to true to make this an async client. -->
        <!-- IMPORTANT!!! Set to true if you would like to also receive data from server. -->

Once you've created the XML file, you can make the client object in setup() and start it!

  // make a new Client using an XML file
  client = new TCPClient(this, "asynch.xml");

Then, whenever you want, send a message. It could be information from a sensor, a microphone or just some protocol you make up! The message will find its way to all of your clients. The code looks like this:

public void mousePressed() {
  client.broadcast("Your message here!");

Or you can broadcast from draw().

client.broadcast("Your message here!");		

If you would like to receive data from the server, make sure you set asynchreceive to tru in your XML file and add a dataEvent() to your sketch.

    // asynchreceive must be set to true in
    // asynch.xml to receive data here
    public void dataEvent(TCPClient c) {
    	println("Raw message: " + c.getRawMessage());
    	if (c.messageAvailable()) {
    		String[] msgs = c.getDataMessage();
    		for (int i = 0; i < msgs.length; i++) {
    			println("Parsed message: " + msgs[i]);

Note: The converse is true as well. If asynchreceive is set to true in the xml file, you must have a dataEvent() in your sketch.