Hi,
I’m using serverEvent, clientEvent and disconnectEvent events to make a basic HTTP server. There seems to be synchronization problems between each events. Here’s my code:
import processing.net.*;
byte[][] Files = new byte[4][];
int HTTPPort = 80;
Server HTTPServer;
ClientInfo[] HTTPClients = new ClientInfo[0];
void setup()
{
fullScreen();
if((Files[0] = loadBytes("NotFound.html")) == null || (Files[1] = loadBytes("Page.html")) == null)
{
exit();
}
else
{
HTTPServer = new Server(this, HTTPPort);
}
}
void draw()
{
saveFrame("Frame.png");
Files[3] = loadBytes("Frame.png");
delay(3000);
background(random(255), random(255), random(255));
}
void serverEvent(Server CurrentServer, Client NewClient)
{
print("New HTTP Client.\r\n");
HTTPClients = (ClientInfo[])append(HTTPClients, new ClientInfo(CurrentServer, NewClient));
}
void clientEvent(Client Client)
{
int i;
String Buffer;
for(i = 0; Client != HTTPClients[i].GetClient(); i += 1);
while((Buffer = HTTPClients[i].GetClient().readStringUntil('\n')) != null)
{
if(Buffer.startsWith("GET /"))
{
HTTPClients[i].SetFile(splitTokens(Buffer, " ?")[1]);
}
else if(Buffer.equals("\r\n"))
{
print("HTTP Request Received.\r\n");
HTTPClients[i].GetClient().write("HTTP/1.1 200 OK\r\n\r\n");
if(HTTPClients[i].GetFile().equals("/"))
{
HTTPClients[i].GetClient().write(Files[1]);
}
else if(HTTPClients[i].GetFile().equals("/favicon.ico"))
{
HTTPClients[i].GetClient().write(Files[3]);
}
else if(HTTPClients[i].GetFile().equals("/Frame.png"))
{
HTTPClients[i].GetClient().write(Files[3]);
}
else
{
HTTPClients[i].GetClient().write(Files[0]);
}
print("HTTP Response Sent.\r\n");
print("Disconnecting HTTP Client.\r\n");
HTTPClients[i].GetClient().stop();
break;
}
}
}
void disconnectEvent(Client OldClient)
{
int i;
for(i = 0; OldClient != HTTPClients[i].GetClient(); i += 1);
for(; i < HTTPClients.length - 1; i += 1)
{
HTTPClients[i] = HTTPClients[i + 1];
}
HTTPClients = (ClientInfo[])shorten(HTTPClients);
print("test\r\n");
}
class ClientInfo
{
int Time;
Server Server;
Client Client;
String File;
ClientInfo (Server CurrentServer, Client NewClient)
{
Time = millis();
Server = CurrentServer;
Client = NewClient;
File = "";
}
Server GetServer()
{
return Server;
}
Client GetClient()
{
return Client;
}
void SetFile(String NewFile)
{
File = NewFile;
}
String GetFile()
{
return File;
}
}
Sometime I get an array index out of bounds (java.lang.ArrayIndexOutOfBoundsException: 0) at line 46. It look like clientEvent is called before serverEvent when a new client connect and send data. I think that’s what happening because the index goes out of bounds only if the Client parameter of clientEvent is not found in the HTTPClients global array (see line 46). The serverEvent, supposed to be called when a new client connect, is responsible for adding new clients in the HTTPClients global array. I’m not sure how to fix this problem, I’m new to Java (I’m used to program in C), any help would be appreciated.
Thanks!