我正在用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);
}
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用以下地址连接到服务器:
http://127.0.0.1:8000/C:/pathtohtmlfile/htmlfile.html
但是,连接超时.我不确定它是C#代码或其他东西的问题.
小智 5
Raymond Zuo的解决方案确实有效.但最重要的是不要忘记的是Packages.appxmanifest中的功能.为了在专用网络中运行服务器,应该添加:
<Capability Name="privateNetworkClientServer" />
Run Code Online (Sandbox Code Playgroud)
并且为了在公共网络中运行服务器:
<Capability Name="internetClientServer" />
Run Code Online (Sandbox Code Playgroud)
小智 4
如果您想在 uwp 应用程序中托管服务器,请确保以下事项:
你应该编写一个方法来获取IP地址,但不是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];
}
}
Run Code Online (Sandbox Code Playgroud)
可以在手机/平板电脑上托管网络服务。
| 归档时间: |
|
| 查看次数: |
8715 次 |
| 最近记录: |