简体   繁体   中英

UDP server to handle multiple clients

I created a UDP server. Here's a skeleton

public class UDPserver {
      public static void main(String[] args) throws Exception{
           while(true){
              .... some code ...
              packet = new DatagramPacket ( data , data.length, packet.getAddress(), packet.getPort() );
              .... some code ...
              socket.receive( ... );
           }
      }
}

Now, i want to make it handle multiple requests, so i checked out that i have to implement Runnable.

public class UDPserver implements Runnable { }

I read that I also need to have a run(). But i don't understand run(). should i put the whole while(true) statement inside run()? what about main()? Can anyone show how to change my code above to handle multiple requests? thanks

move all the code inside the run method of UDPServer (including the while(true))

In your main method :


UDPServer udpServer = new UDPServer();
udpServer.start();

  • To make sure that no excpetion won't break your main loop, remember to catch and handle all exceptions that might be rasied inside the while(true) loop

You can also use new thread for each new connection for performing. For example:

 class PacketPerforming extends Thread {
 DatagramPacket pak; 
 PacketPerforming(DatagramPacket pak) {
  super();
  this.pak = pak;
 } 

 public void run() {
  // do somethoing with pak
 }

 }

 // in your server thread
 while (true) { // i prefered wirte for (;;)

  DatagramPacket pak; // take pak object form remote socket

  PacketPerforming perform = new PacketPerforming(pak);
  perform.start();

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM