123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- using System;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using UnityEngine;
- public class WebServer : MonoBehaviour
- {
- private TcpListener listener;
- private string rootDirectory;
- private const string DefaultFileName = "index.html";
- private const string NotFoundFileName = "404.html";
- public int port = 8080;
- public string directory = "wwwroot";
- void Start()
- {
- rootDirectory = Path.Combine(Application.streamingAssetsPath, directory);
- listener = new TcpListener(IPAddress.Any, port);
- listener.Start();
- Debug.Log("Web server started on port " + port);
- }
- void Update()
- {
- if (listener.Pending())
- {
- TcpClient client = listener.AcceptTcpClient();
- HandleRequest(client);
- }
- }
- void HandleRequest(TcpClient client)
- {
- NetworkStream stream = client.GetStream();
- StreamReader reader = new StreamReader(stream);
- StreamWriter writer = new StreamWriter(stream);
- string request = reader.ReadLine();
- Debug.Log("Request: " + request);
- string[] tokens = request.Split(' ');
- string method = tokens[0];
- string url = tokens[1];
- if (url == "/")
- {
- url += DefaultFileName;
- }
- string filePath = Path.Combine(rootDirectory, url.Substring(1));
- if (File.Exists(filePath))
- {
- string contentType = GetContentType(filePath);
- byte[] fileBytes = File.ReadAllBytes(filePath);
- writer.Write("HTTP/1.0 200 OK\r\n");
- writer.Write("Content-Type: " + contentType + "\r\n");
- writer.Write("Content-Length: " + fileBytes.Length + "\r\n");
- writer.Write("\r\n");
- writer.Flush();
- stream.Write(fileBytes, 0, fileBytes.Length);
- }
- else
- {
- string notFoundPath = Path.Combine(rootDirectory, NotFoundFileName);
- if (File.Exists(notFoundPath))
- {
- byte[] notFoundBytes = File.ReadAllBytes(notFoundPath);
- writer.Write("HTTP/1.0 404 Not Found\r\n");
- writer.Write("Content-Type: text/html\r\n");
- writer.Write("Content-Length: " + notFoundBytes.Length + "\r\n");
- writer.Write("\r\n");
- writer.Flush();
- stream.Write(notFoundBytes, 0, notFoundBytes.Length);
- }
- }
- writer.Close();
- reader.Close();
- client.Close();
- }
- string GetContentType(string filePath)
- {
- string extension = Path.GetExtension(filePath);
- switch (extension)
- {
- case ".html":
- case ".htm":
- return "text/html";
- case ".css":
- return "text/css";
- case ".js":
- return "text/javascript";
- case ".jpg":
- case ".jpeg":
- return "image/jpeg";
- case ".gif":
- return "image/gif";
- case ".png":
- return "image/png";
- default:
- return "application/octet-stream";
- }
- }
- void OnDestroy()
- {
- listener.Stop();
- }
- }
|