Creating a web server in C# UWP

2020-04-05 17:56发布

问题:

I am writing a web server as a Universal Windows Platform app in C#. Here is my code so far:

sealed partial class App : Application
    {
        int port = 8000;

        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            StartServer();
        }

        private void StartServer()
        {
            StreamSocketListener listener = new StreamSocketListener();
            listener.BindServiceNameAsync(port.ToString());
            Debug.WriteLine("Bound to port: " + port.ToString());
            listener.ConnectionReceived += async (s, e) =>
                {
                    Debug.WriteLine("Got connection");
                    using (IInputStream input = e.Socket.InputStream)
                    {
                        var buffer = new Windows.Storage.Streams.Buffer(2);
                        await input.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);       
                    }

                    using (IOutputStream output = e.Socket.OutputStream)
                    {
                        using (Stream response = output.AsStreamForWrite())
                        {
                            response.Write(Encoding.ASCII.GetBytes("Hello, World!"), 0, 1);
                        }
                    }
                };
        }
    }

I tried connecting to the server using this address:

http://127.0.0.1:8000/C:/pathtohtmlfile/htmlfile.html

However, the connection times out. I am not sure if it is a problem with the C# code or with something else.

回答1:

Raymond Zuo's solution really works. But the main thing not to forget are capabilities in Packages.appxmanifest. In order to run the server in Private networks one should add:

<Capability Name="privateNetworkClientServer" />

And in order to run the server in Public network:

<Capability Name="internetClientServer" />


回答2:

If you want to host a server in uwp app, be sure these things:

  1. your device which run this code (Device A) and device which your web browser run (Device B) must at a same LAN. And you cannot use the browser in Device A to access your service.
  2. use WIFI to access your service.
  3. your app must be at the state of running.
  4. you should write a method to get ip address, but not 127.0.0.1:

    public static string FindIPAddress()
    {
        List<string> ipAddresses = new List<string>();
        var hostnames = NetworkInformation.GetHostNames();
        foreach (var hn in hostnames)
        {
            //IanaInterfaceType == 71 => Wifi
            //IanaInterfaceType == 6 => Ethernet (Emulator)
            if (hn.IPInformation != null && 
                (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71 
                || hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
            {
                string ipAddress = hn.DisplayName;
                ipAddresses.Add(ipAddress);
            }
        }
    
        if (ipAddresses.Count < 1)
        {
            return null;
        }
        else if (ipAddresses.Count == 1)
        {
            return ipAddresses[0];
        }
        else
        {
            return ipAddresses[ipAddresses.Count - 1];
        }
    }
    

    It is possible to host a web service on phone/tablet.



回答3:

It is possible to host a web service in a Window Universal App. I followed the example from http://www.dzhang.com/blog/2012/09/18/a-simple-in-process-http-server-for-windows-8-metro-apps , also followed the three first steps from Raymond Zuo's solution and finally I also put the firewall down. Unfortunately, I was not able to run on localhost even though I followed the answers from here Cannot connect to localhost in windows store application . I am currently doing java http requests to the Universal Platform App. Definitely, server and client seem to be required to run on different hosts.



标签: c# webserver uwp