How do I run the server without using a while loop?
•
Java
I'm trying to create a server program using datagram socket and datagram packet classes, but my current code uses an ugly while loop, which also freezes my program when the server runs, but the server runs well without any problems In any case, the code is as follows Anyway, can I use something different from the while loop or prevent the while loop from blocking any other code in the program?
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
}
}
}
Solution
You should put it in a new thread The process of receiving packets involves synchronous IO, so it will always block any thread it runs
For clarity, it is not the while loop itself that causes the rest of the program to wait This is socket Receive() call
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
