簡體   English   中英

在 C# 中使用相同 UDP 端口的多個程序/實例

[英]Multible programs/instances using the same UDP Port in C#

我正在為一些網絡魔法而苦苦掙扎,並希望有人能夠向我解釋正在發生的事情。

我正在嘗試重用 udp 端口。 因此,如果我有多個程序在同一個 udp 端口上偵聽,我希望這兩個應用程序都接收不同設備發送的數據。

使用以下代碼,我能夠做到這一點:

            IPEndPoint localEndoint = new IPEndPoint(IPAddress.Any, 67);    //the local endpoint used to listen to port 67
            //Create a new UDP Client and bind it to port 67
            DhcpSniffer = new UdpClient();
            DhcpSniffer.ExclusiveAddressUse = false;    //Allow multible clients to connect to the same socket
            DhcpSniffer.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Connect even if socket/port is in use
            DhcpSniffer.Client.Bind(localEndoint);
            DhcpSniffer.Client.ReceiveTimeout = Timeout;
            //receive on port 67 
            dhcpPacket = DhcpSniffer.Receive(ref localEndoint);

我的兩個程序都可以監聽網絡中的 DHCP 消息,並且不會互相阻塞。 現在我想對端口 15120 做同樣的事情,RTP 視頻 stream 被流式傳輸到該端口。 但是,這不起作用。 我正在使用相同的代碼,但沒有成功,一次只有一個應用程序可以接收 stream,另一個將超時運行。

            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, port);
            //Create a new UDP Client and bind it to port 15120
            udpReceiver = new UdpClient();
            udpReceiver.ExclusiveAddressUse = false;    //this is an attempt to receive the stream on mutlible instances...this works for DHCP but not for RTP for some reason....
            udpReceiver.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // Connect even if socket/port is in use
            udpReceiver.Client.ReceiveTimeout = timeout;    //set the sockete timeout
            udpReceiver.Client.Bind(RemoteIpEndPoint);      //bind to the port from any IP
            //receive packets on port 15120
            Byte[] receiveBytes = udpReceiver.Receive(ref RemoteIpEndPoint);

我希望有人能夠照亮我的困惑

更新:我發現它適用於 DHCP,因為它被發送到廣播 IP (255.255.255.255)。 現在我需要了解如何更改 Socket 行為以將我的 RTP stream 視為已廣播,以便我可以同時在兩個應用程序中看到它。 (是的,我可以將我的流源配置為廣播,但這不是目標)。 目標是重新配置 Socket 以按照解釋的方式運行。 不要將 stream 保存在硬盤驅動器上或使用本地主機重定向它。

首先,不可能有多個程序在同一個端口上監聽(據我所知這是一個很大的安全沖突)

你可以做的是使用 NetworkManager 監聽你的端口(我們稱之為端口 8080),然后將信息重定向到你的應用程序端口(App1 可以使用端口 8081,App2 使用端口 8082)。 您可以自己編寫,使用 Flask 監聽 8080,然后將 package 重新路由到 localhost:8081 和 localhost:8082 可能是一個簡單而快速的解決方案。

這樣做可以幫助您保護網絡,並且您可以根據需要重定向到任意數量的端口,就像 docker 集群將傳入網絡平衡到其集群一樣。

多個程序無法從單播 UDP package 訪問數據,它僅適用於多播,沒有通過重新配置 UdpClient 來解決此問題的“簡單”方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM