Sending and receiving UDP packets between two programs on the same computer

后端 未结 8 1814
慢半拍i
慢半拍i 2020-12-02 12:37

Is it possible to get two separate programs to communicate on the same computer (one-way only) over UDP through localhost/127... by sharing the same port #?

We\'re

8条回答
  •  我在风中等你
    2020-12-02 12:57

    I did not expect this to be possible, but.. well.. sipwiz was right.

    It can be done very easily. (Please vote sipwiz's answer up!)

    IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);
    
    //Failed try
        try
        {
            var u = new UdpClient(5000);
            u.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    
            UdpClient u2 = new UdpClient(5000);//KABOOM
            u2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        }
        catch (Exception)
        {
            Console.WriteLine("ERROR! You must call Bind only after setting SocketOptionName.ReuseAddress. \n And you must not pass any parameter to UdpClient's constructor or it will call Bind.");
        }
    
    //This is how you do it (kudos to sipwiz)
        UdpClient udpServer = new UdpClient(localpt); //This is what the proprietary(see question) sender would do (nothing special) 
    
        //!!! The following 3 lines is what the poster needs...(and the definition of localpt (of course))
        UdpClient udpServer2 = new UdpClient();
        udpServer2.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        udpServer2.Client.Bind(localpt);
    

提交回复
热议问题