使用HttpListener实现简单Web服务器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Unity C# 脚本,使用 HttpListener 实现加密签名: ```csharp using System; using System.Net; using System.Text; using System.Security.Cryptography; using UnityEngine; public class HttpListenerExample : MonoBehaviour { private HttpListener listener; // 在启动时运行 void Start() { // 创建 HttpListener 对象 listener = new HttpListener(); // 添加要监听的 URI listener.Prefixes.Add("http://localhost:8080/"); // 启动监听器 listener.Start(); // 开始异步处理传入请求 listener.BeginGetContext(ProcessRequest, null); } // 处理传入请求 void ProcessRequest(IAsyncResult result) { // 获取请求上下文 HttpListenerContext context = listener.EndGetContext(result); // 获取请求对象 HttpListenerRequest request = context.Request; // 获取请求数据 byte[] requestData = Encoding.UTF8.GetBytes(request.QueryString.ToString()); // 获取签名 string signature = GetSignature(requestData, "your_secret_key_here"); // 返回签名 byte[] responseData = Encoding.UTF8.GetBytes(signature); context.Response.ContentType = "text/plain"; context.Response.ContentLength64 = responseData.Length; context.Response.OutputStream.Write(responseData, 0, responseData.Length); // 关闭响应 context.Response.Close(); // 继续异步处理传入请求 listener.BeginGetContext(ProcessRequest, null); } // 获取签名 string GetSignature(byte[] data, string secretKey) { // 使用 HMAC-SHA256 算法计算签名 using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey))) { byte[] hash = hmac.ComputeHash(data); return BitConverter.ToString(hash).Replace("-", "").ToLower(); } } // 在停止时运行 void OnDestroy() { // 停止监听器 listener.Stop(); listener.Close(); } } ``` 请注意,这个示例仅仅演示了如何使用 HttpListener 实现加密签名。在实际应用中,您需要根据您的具体需求进行修改和扩展。同时,建议对密钥进行加密保护,并使用 HTTPS 等安全协议来保证传输的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值