2012-12-20 5 views
0

단일 포트에서 멀티 캐스트, UDP 및 TCP 트래픽을 수신 대기하고 싶습니다. (내 LAN에서) 뭔가가 발견되면 UDP를 통해 응답하고 싶습니다.Java - UDP 및 멀티 캐스트 감지

코드는 아래에서 작동하지만 멀티 캐스트 검색에서만 작동합니다. while (true) 루프는 main()에서 확실히 수행합니다.

하지만 저는 다른 프로토콜 탐지 방법을 추가하여 벽에 뛰어 들고 있습니다. 하나의 응용 프로그램에서 여러 프로토콜로 여러 소켓을 열 수 있습니까? 스레딩에 대한 제한된 지식이라고 확신하지만 어쩌면 누군가 내 문제를 볼 수 있습니다.

public class LANPortSniffer { 

    private static void autoSendResponse() throws IOException { 

    String sentenceToSend = "I've detected your traffic"; 
    int PortNum = 1234; 

    DatagramSocket clientSocket = new DatagramSocket(); 
    InetAddress IPAddress = InetAddress.getByName("192.168.1.121"); 
    byte[] sendData = new byte[1024]; 

    sendData = sentenceToSend.getBytes(); 
    DatagramPacket sendPacket = 
     new DatagramPacket(sendData, sendData.length, IPAddress, PortNum); 
    clientSocket.send(sendPacket); 
    clientSocket.close(); 


    }//eof autoSendResponse 


    private static void MulticastListener() throws UnknownHostException { 

    final InetAddress group = InetAddress.getByName("224.0.0.0"); 
    final int port = 1234; 

    try { 

     System.out.println("multi-cast listener is started......"); 
     MulticastSocket socket = new MulticastSocket(port); 
     socket.setInterface(InetAddress.getLocalHost()); 
     socket.joinGroup(group); 

     byte[] buffer = new byte[10*1024]; 

     DatagramPacket data = new DatagramPacket(buffer, buffer.length); 

     while (true) { 
      socket.receive(data); 

      // auto-send response 
      autoSendResponse(); 

     } 


     } catch (IOException e) { 
     System.out.println(e.toString()); 
     } 

    }//eof MulticastListener 

// this method is not even getting launched 
private static void UDPListener() throws Exception { 

    DatagramSocket serverSocket = new DatagramSocket(1234); 
    byte[] receiveData = new byte[1024]; 

    System.out.println("UDP listener is started......"); 
    while(true) 
     { 
      DatagramPacket receivePacket = 
       new DatagramPacket(receiveData, receiveData.length); 
      serverSocket.receive(receivePacket); 
      String sentence = new String(receivePacket.getData()); 
      System.out.println("UDP RECEIVED: " + sentence); 

     }  

} 



    public static void main(String[] args) throws Exception { 
      //Schedule a job for the event-dispatching thread: 
      //creating and showing this application's GUI. 
      javax.swing.SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        createAndShowGUI(); 
       } 
      }); 


      try { 
      MulticastListener(); 

     } catch (UnknownHostException e) { 

      e.printStackTrace(); 
     } 


      // this does not appear to be detected: 
      try { 
      UDPListener(); 

     } catch (Exception e) { 

      e.printStackTrace(); 
     } 


    } 
}//eof LANPortSniffer 

main()에서 간단한 UDPListener() 메소드에 두 번째 try/catch를 추가하려고 시도했습니다.
하지만 Eclipse에서 응용 프로그램을 실행할 때 무시되는 것 같습니다.

main() 메소드는 하나의 try/catch 만 허용합니까?

간단히 말해서 멀티 캐스트, UDP 및 TCP 패킷을 모두 한 번 포트에서 수신하고 싶습니다. 이것이 가능한가?

답변

2

여기 스레딩 문제가 발생했습니다. 나는 당신이 자바에 대한 이해를 쌓아야한다고 생각한다. MulticastListener()으로 전화하면 연결이 끊어 질 때까지 해당 블록을 떠나지 않습니다. 그것은 while 루프를 반복합니다. 이러한 각 액티비티에 대해 새 스레드를 만들어야합니다.

Thread t = new Thread(new Runnable() { 
    public void run() { 
     MulticastListener(); 
    } 
} 
t.start(); 

그러나 나는 당신이 스레드 프로그램을 구현하기 위해 노력하고 시작하기 전에 프로그램의 흐름과 더 객체 지향 접근 방식의 사용의 당신이 당신의 이해를 읽어 좋습니다.

0

1) 멀티 캐스트 수신기를 사용하지 않는 원시 소켓 액세스가 필요합니다. 2) Java의 무차별 모드 및 원시 소켓 조회. 3) 스레딩 문제는 관련성이 낮습니다. 코드를 개선하기 전에 하나의 스레드로 작업하게하는 것이 좋습니다.

관련 문제