Processing Month, Day 24 - Client/Server Part 2

Posted on 2011-05-24 by Jan Vantomme
Tags: processing, tutorial

In part two of Client/Server programming with Processing, we'll take a look at creating the client application. You need to create a new client object with the same port number as the server. If you run the client sketch on the same machine, you can use 127.0.0.1 for the IP Address, if it runs on another computer, you need to use the IP Address of the machine that runs the server sketch.

client = new Client( this, "127.0.0.1", 5000 );

We also need a function to convert the byte array back to an integer. You can find this one in the functions tab.

int byteArrayToInt(byte[] bytes) {
    int bits = 0;
    int counter = 0;
    for (int i = 3; i >= 0; i--) {
        bits |= ((int) bytes[counter] & 0xff) << (i * 8);
        counter++;
    }
    return bits;
}

The final thing we need to do is to read the data the server application is sending with clients.readBytesUntil() into a bytebuffer and get the x and y coordinates out of there for drawing ellipses and lines to the screen.

if ( client.available() > 0 ) {
    int byteCount = client.readBytesUntil( interesting, byteBuffer );
    byte[] xb = new byte[4];
    for (int i = 0; i < 4; i++) {
        xb[i] = byteBuffer[i];
    }
    byte[] yb = new byte[4];
    for (int i = 0; i < 4; i++) {
        yb[i] = byteBuffer[i+4];
    }
    int x = byteArrayToInt( xb );
    int y = byteArrayToInt( yb );
    line( x, y, prevX, prevY );
    ellipse( x, y, 10, 10 );
    prevX = x;
    prevY = y;
}

Screencast

I've created a screencast so you can see what the application does. You can find it on Vimeo.

Download

Download the client sketch you've read about today. I've included the server sketch from yesterday.

Tweet this article