c# - 在 C# UWP 中创建 Web 服务器

标签 c# webserver uwp

我正在用 C# 编写一个 Web 服务器作为通用 Windows 平台应用程序。到目前为止,这是我的代码:

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# 代码还是其他问题。

最佳答案

Raymond Zuo 的解决方案确实有效。但不要忘记的主要事情是 Packages.appxmanifest 中的功能。为了在专用网络中运行服务器,应该添加:

<Capability Name="privateNetworkClientServer" />

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

<Capability Name="internetClientServer" />

关于c# - 在 C# UWP 中创建 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33559129/

相关文章:

c# - Microsoft Orleans grain 通信性能

c# - Index was outside the bounds of the array 异常

python - 一个好的多线程 python 网络服务器?

ubuntu - 监控和降低高 CPU 使用率

c# - UWP - 语言的变化

c# - 在 ASP.NET 中使用静态变量代替应用程序状态

asp.net - 推出整个网站,还是仅更改页面/元素? (ASP.NET)

c# - 以全屏模式运行的 UWP C# 应用程序在全屏观看视频后切换到窗口模式

xaml - "Shortcut"用于设置ListViewItem选定背景

c# - 从服务器托管应用程序时如何获取用户文件的本地桌面路径?