Processing Month, Day 23 - Client/Server Part 1

Posted by Jan Vantomme on 23 May 2011.
Tags:

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 Serverthis5000 ); 

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.writegetMousePositionAsByteArray() ); 

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 04i++) {
        int offset 
= (result.length 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 
intToByteArraymouseX );
    
byte[] y intToByteArraymouseY );    
    
byte[] b = new byte[9];
    for (
int i 04i++) {
        b[i] 
x[i];
    
}
    
for (int i 48i++) {
        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