I’m building a real-time GPS tracking system, which will receive GPS data sent from a couple of Arduino devices using UDP. I have this code so far:
PreparedStatement stmt ...
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
while(true){
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String received = new String( receivePacket.getData());
System.out.println("RECEIVED: " + received);
stmt.set...
stmt.execute();
}
1 – Anyone with more knowledge could tell me if there’s a better way of doing this? I really don’t know how the JVM handles this, but I don’t like that infinite loop.
2 – Lets say that I have 50 Arduinos sending data. I need to use threads or something like this?
3 – It’s best to use a thread per “connection” (UDP is connectionless) like an answer below or use frameworks/libs like Apache Mina or Netty?
There is no problem using an infinite loop in this case. Calling receive waits until a new datagram is delivered:
So no CPU power is wasted here, it simply waits until new data is available.
If you have many clients or if processing the packet isn’t completely trivial, you should start a new thread for processing each one, so that the main thread that receives the datagrams doesn’t get blocked. Probably the best approach is to use thread pools that will create threads for you, and at the same time prevent creating too many threads if your application is overloaded by requests.
I’d proceed as follows:
Create a dedicated thread for receiving the datagrams. It could also create a thread pool for dispatching processing the requests. Something like:
Create class
YourTaskthat processes the datagrams: