简体   繁体   中英

HTTP over UDP adapter for Web API

I need to send some data from mobile clients to an ASP.NET ApiController. I cannot wait for an connection to be established (and I don't rely on the data to arrive), so I thought UDP is the way to go. On the server I need to listen on a UDP endpoint and redirect the request to my default HTTP endpoint.

This is what I have so far (shortened):

public class HttpOverUdpAdapter
{
    public static UdpClient UpdListener;

    public static void Start(int udpPort, tcpPort)
    {
        UpdListener = new UdpClient(udpPort);

        new Thread(() =>
        {
            while (true)
            {
                IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, udpPort);
                byte[] bytes = UpdListener.Receive(ref endpoint);

                TcpClient client = new TcpClient();
                client.Connect(IPAddress.Loopback, tcpPort);
                using (NetworkStream stream = client.GetStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
            }
        }).Start();
    }
}

I get the following error when no matter what port I use:

System.Net.Sockets.SocketException: Only one usage of each socket address (protocol/network address/port) is normally permitted.

Apart from that, is this going to work out at all? Is it correct to start it in Application_Start() ?

Remark: WCF is no alternative.

There is no such thing as "I don't rely on the data to arrive" with HTTP. HTTP consists of requests and responses, which are usually big enough so that multiple IP packets are needed. UDP does neither guarantee the delivery nor the order of the packets, so you might end up with corrupt requests which might result in no response (which might be ok for you) or in a response for another web resource (which is probably not ok). Also, the response can be corrupt too in an unpredictable way (which is probably not ok for you).

If you would a need a more reliable transport you would add a reliability layer on top of the UDP tunnel, which is neither simpler nor faster than simply using TCP directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM