在单个端口上,我想监听多播、UDP 和 TCP 流量。(在我的局域网上)如果检测到某些东西,我也想通过 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() 方法是否只允许一次尝试/捕获?
简而言之,我想在一个端口上同时监听多播、UDP 和 TCP 数据包。这可能吗?