我正在尝试在Unity3D游戏中用c#创建一个简单的https服务器,以便通过Web浏览器访问。我已经使用openssl创建了服务器证书和密钥,但我无法找到一种多平台方式将证书传递给服务器,而无需在代码外部进行任何其他配置。
我能找到的大部分信息都属于这些类别:
我在python中知道你做了类似的事情:
ssl.wrap_socket (httpd.socket, certfile='./server-crt.pem', keyfile='./server-key.pem', server_side=True)
...但是对于httplistener,或者在system.security.securitymanager或其他任何东西中,它似乎不是c#中的等价物。我认为/希望我在这里遗漏了一些明显的东西。
对于它的价值,这里是我目前所拥有的,这只是放在Unity脚本中的MSDN httplistener示例:
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 () {
}
}
答案 0 :(得分:0)
如果您来自Google,试图在Mono和SSL中找到有关HttpListener的信息,您将找到有关此相关问题的更多相关信息:
Mono HttpListener client certificate
OP最初希望的是没有任何平台特定配置的简单Web服务器。到目前为止,我发现的唯一支持这种避免平台配置方法的库是Ceen HTTPd。
此处有类似需求的海报中有关于Ceen的讨论: https://softwarerecs.stackexchange.com/questions/52304/net-library-for-running-an-embedded-selfhosted-light-web-server-from-c-with-ss