Processing Month, Day 23 - Client/Server Part 1

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

Today and tomorrow, we'll dive into the dark art of communication between computers. We'll use the Network library that is included with Processing. The server application we'll create today will send the mouse position to the client application we'll create tomorrow. You should start a server inside setup() and use a port number that is high enough. I'm using port number 5000 in this example.

server = new Server( this, 5000 );

We're going to keep this program as simple as possible. The only piece of code that goes inside draw() is the line below. The server.write() method is part of the Network library, the getMousePositionAsByteArray() function is one we're going to write ourselves.

server.write( getMousePositionAsByteArray() );

To communicate to the client application, we need to send the info as bytes. The mouseX and mouseY variables are integers (stored in memory as 32 bits) so we need to convert each integer to a byte Array with a length of 4.

byte[] intToByteArray(int number) {
    byte[] result = new byte[4];
    for (int i = 0; i < 4; i++) {
        int offset = (result.length - 1 - i) * 8;
        result[i] = (byte) ((number >>> offset) & 0xff);
    }
    return result;
}

To send the mouse position to the client application, we need to create an array with the x and y position and an extra byte at the end so we can 'sync' the client application with the server. This function creates a byte Array with a length of 9 and fills it with the mouse position and the separator byte.

byte[] getMousePositionAsByteArray()
{
    byte[] x = intToByteArray( mouseX );
    byte[] y = intToByteArray( mouseY );    
    byte[] b = new byte[9];
    for (int i = 0; i < 4; i++) {
        b[i] = x[i];
    }
    for (int i = 4; i < 8; i++) {
        b[i] = y[i-4];
    }
    b[8] = 10; // separator byte
    return b;
}

Download

Download the server sketch you've read about today.

Tweet this article