在C#UWP中创建Web服务器 [英] Creating a web server in C# UWP
问题描述
我正在使用C#将Web服务器编写为通用Windows平台应用程序.到目前为止,这是我的代码:
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
但是,连接超时.我不确定C#代码还是其他问题.
However, the connection times out. I am not sure if it is a problem with the C# code or with something else.
推荐答案
Raymond Zuo的解决方案确实有效.但是最重要的是Packages.appxmanifest中的功能.为了在专用网络中运行服务器,应添加:
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" />
这篇关于在C#UWP中创建Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!