我正在尝试在Unity3D游戏中使用C#创建一个简单的https服务器,以通过Web浏览器访问。我已经使用openssl创建了服务器证书和密钥,但是我找不到一种跨平台的方式来将证书传递给服务器,而不需要在代码外进行任何其他配置。
我找到的大部分信息属于以下几类:
- 使用SslStream,但似乎只与TcpListener相关(我想要更高级别的东西,可以提供网页服务) - 需要外部仅限Windows的工具,如httpcfg,我不想使用 - 在证书存储中编程或手动安装证书,这似乎需要程序或用户拥有管理员/根权限
我知道在Python中你可以做这样的事情:
我找到的大部分信息属于以下几类:
- 使用SslStream,但似乎只与TcpListener相关(我想要更高级别的东西,可以提供网页服务) - 需要外部仅限Windows的工具,如httpcfg,我不想使用 - 在证书存储中编程或手动安装证书,这似乎需要程序或用户拥有管理员/根权限
我知道在Python中你可以做这样的事情:
ssl.wrap_socket (httpd.socket, certfile='./server-crt.pem', keyfile='./server-key.pem', server_side=True)
...但是似乎在C#中并没有类似于httplistener的等效物,也没有system.security.securitymanager或其他任何东西。我假设/希望我只是漏掉了一些显而易见的东西。
值得一提的是,这是我目前为止所拥有的,只是将MSDN httplistener示例放入Unity脚本中:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
public class SimpleListenerExample : MonoBehaviour {
// This example requires the System and System.Net namespaces.
public static void StartServer(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
/* and here's the part where I would load the server certificate ...somehow */
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}
// Use this for initialization
void Start () {
String[] prefixes = { "http://*:8089/", "https://*:8443/" };
StartServer(prefixes);
}
// Update is called once per frame
void Update () {
}
}