简体   繁体   中英

java thread and datagram socket receiving

I am new to both datagram sockets and threading. When I run the code in my command prompt I was expecting to see both 6500 and 6501 printing out but only saw 6500. Why is the code not running the second start()? How can I thread multiple receiving datagram sockets (easiest way, not necessarily best way)?

public class startThread {
public static void main(String[] args) throws Exception, IOException {
    new routerInterface(6500, "receive").start();
    new routerInterface(6501, "receive").start();
}
}

public routerInterface(int virPort, String action) throws Exception{
    System.out.println(virPort);
    if (action.compareTo("receive")==0){
        request = new DatagramSocket(clientPort);
        receive();
    }
}

public static void receive() throws Exception{
      while(true) { 
          System.out.println("We are recieving here");
          DatagramPacket p = new DatagramPacket(udpPack, udpPack.length);  
          request.receive(p);
          byte[] reciv = p.getData();
      }
}

您需要从run()方法而不是构造函数中调用receive()

Looks like you receive in constructor rather than run method. So first one is blocking. Second never starts.

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