I'm trying to make a server program using the DatagramSocket and DatagramPacket classes, but my current code uses an ugly while loop which also freezes my program while the server runs, but the server runs fine with no problems. Anyway the code is below. Is there anyway I can use something different than a while loop or prevent the while loop from preventing any other code in the program to execute?
protected void run() {
try {
socket = new DatagramSocket(port);
socket.setBroadcast(true);
} catch (Exception e) {
e.printStackTrace();
stopServer(); //stop the server
return;
}
while(isRunning()){ //hate this loop
try {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, 256);
socket.receive(packet);
DatagramPacket serverPacket;
byte[] serverBuf;
byte hb = 0;
byte lb = packet.getData()[0];
int e = ((int)hb<<8)|((int)lb&0xFF); //translate byte to int
switch(e) {
case 2:
//do something
break;
case 5:
//do something
break;
case 7:
//do something
break;
default:
//default stuff
break;
}
} catch (Exception e) {
System.out.println("Fatal Server Error:");
e.printStackTrace();
stopServer(); //stop the server
return; //stop the method
}
}
}
You should put this in a new thread. The process of receiving a packet involves synchronous IO, so it will always block whichever thread it's running in.
To clarify, it's not the while loop itself that makes the rest of the program wait. It's the socket.receive() call.