金铉Unity插件库 Unity版本2018.4.32f 目前包含本地化存储功能(根据类名存储读写),TCP客户端监听类型功能
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.6 KiB

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using UnityEngine;
public class HttpServerView : MonoBehaviour
{
public string[] prefixes;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void startListen() {
SimpleListenerExample(prefixes);
}
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Debug.Log("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://127.0.0.1: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);
}
listener.Start();
Debug.Log("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
#region 解析Request请求
HttpListenerRequest request = context.Request;
string content = "";
switch (request.HttpMethod)
{
case "POST":
{
Stream stream = context.Request.InputStream;
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
content = reader.ReadToEnd();
Debug.Log(content);
}
break;
case "GET":
{
var data = request.QueryString;
Debug.Log(data);
}
break;
}
#endregion
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
byte[] buffer = Encoding.UTF8.GetBytes("<HTML><BODY> " + request.InputStream + "</BODY></HTML>");
// 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();
}
}