Skip to content

Instantly share code, notes, and snippets.

@PikaChokeMe
Forked from amimaro/UnityHttpListener.cs
Last active March 5, 2023 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PikaChokeMe/7604fa19596ea6f66019898a948a8dd2 to your computer and use it in GitHub Desktop.
Save PikaChokeMe/7604fa19596ea6f66019898a948a8dd2 to your computer and use it in GitHub Desktop.
Listen for Http Requests with Unity
using UnityEngine;
using UnityEngine.Networking;
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
public class UnityHttpListener : MonoBehaviour
{
private HttpListener listener;
void Start()
{
listener = new HttpListener();
listener.Prefixes.Add("http://localhost:4444/");
listener.Prefixes.Add("http://127.0.0.1:4444/");
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Start();
StartCoroutine("startListenerCoroutine");
Debug.Log("Server Started");
}
private System.Collections.IEnumerator startListenerCoroutine()
{
while(listener.IsListening)
{
Task<HttpListenerContext> task = listener.GetContextAsync();
yield return new WaitUntil(() => task.IsCompleted);
ProcessRequest(task.Result);
}
}
private void ProcessRequest(HttpListenerContext context)
{
Debug.Log("Method: " + context.Request.HttpMethod);
Debug.Log("LocalUrl: " + context.Request.Url.LocalPath);
if (context.Request.QueryString.AllKeys.Length > 0) {
foreach (var key in context.Request.QueryString.AllKeys) {
Debug.Log ("Key: " + key + ", Value: " + context.Request.QueryString.GetValues (key) [0]);
}
}
if (context.Request.HttpMethod == "POST") {
var data_text = new StreamReader (context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();
Debug.Log (data_text);
}
context.Response.StatusCode = 200;
context.Response.StatusCode = "OK";
context.Response.Close();
}
void OnApplicationQuit() {
listener.Stop();
Debug.Log("Server stoped");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment