如何同时在单个端口上运行tcp和udp?

问题描述:

我遇到这样的情况,例如必须同时在单个端口上同时运行UDP和TCP.这是因为在我的应用程序中,任何人都可以随时调用任何协议.因此,我需要不断检查传入的请求并处理该请求.谁能帮助我摆脱Java中的这种情况?

I have a situation like I have to run UDP and TCP both on a single port at a time. This is because in my application at any time anyone can call for any protocol. So I need to continously check the incoming request and serve the request. Can anyone pls help me to get rid of this situation in java?

您无法检查请求是TCP还是UDP.而是添加一个侦听器(即TCP)和一个侦听器(即UDP).如果您使用广播或多播地址,则IMHO UDP更有用.

You can't check whether a request is TCP or UDP. Instead you add a listener which is TCP and a listener which is UDP. IMHO UDP is more useful if you use a broadcast or multi-cast address.

例如

ServerSocket ss = new ServerSocket(12345);
DatagramSocket ds = new DatagramSocket(12345);

ServerSocket ss = new ServerSocket(12345);
DatagramSocket ds = new MulticastSocket(new InetSocketAddress("224.224.1.1", 12345));

在两种情况下,tcp连接都转到ServerSocket,而udp数据包转到DatagramSocket

In both cases, tcp connections go to the ServerSocket and udp packets go to the DatagramSocket