在C# UWP中创建Web服务器

8

我正在使用C#编写一个作为通用Windows平台应用程序的Web服务器。以下是我的代码:

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);
                        }
                    }
                };
        }
    }

我尝试使用以下地址连接服务器:

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

然而,连接超时了。我不确定是C#代码出了问题还是其他原因。


你看过这个吗:http://loopback.codeplex.com/? WinRT和UWP应用程序有一个回环保护,该工具将为指定的应用程序删除它。也许这就是你需要的。 - MrCSharp
很不幸,loopback异常仅适用于客户端套接字。 - George Birbilis
3个回答

8

Raymond Zuo的解决方案真的很有效。但是不要忘记在Packages.appxmanifest中添加权限。为了在私有网络中运行服务器,应该添加以下内容:

<Capability Name="privateNetworkClientServer" />

为了在公共网络中运行服务器:

<Capability Name="internetClientServer" />

4

如果你想在uwp应用中托管服务器,请确保以下几点:

  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.


你有WinRT中托管Web服务的示例吗?我找到的所有内容都根本不起作用。 - CodeNoob
3
我喜欢"else if"和"else"的构造,它们看起来毫无意义 ;-D - Jens Marchewka

1
可以在Windows通用应用程序中托管Web服务。我按照http://www.dzhang.com/blog/2012/09/18/a-simple-in-process-http-server-for-windows-8-metro-apps的示例进行操作,还遵循了Raymond Zuo解决方案的前三个步骤,最后我也关闭了防火墙。不幸的是,即使我按照这里的答案Cannot connect to localhost in windows store application的回答进行操作,我仍然无法在本地主机上运行。目前,我正在对通用平台应用程序执行Java HTTP请求。显然,服务器和客户端似乎需要在不同的主机上运行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接