gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:16:57 25 4
gpt4 key购买 nike

我正在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com