HoloLabInc / UniWebServer

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The cancel token takes no effect.

Bian-Sh opened this issue · comments

编辑器下多次运行 UniWebServer 后,Unity 有几率会展示端口不可重复使用的报错。

The port error didn't happen in my environment.
Could you explain the situation in which the error occurs?

目前没发现问题,但会持续关注的,如果再次发现再讨论吧,谢谢你的回复与关注~~
当然我也做了一些修改,你可以理解是一种无厘头的防御式编程**吧。

using System;
using System.Net;
using System.Threading;
using static HoloLab.UniWebServer.Loom;

namespace HoloLab.UniWebServer
{
    public class HttpServer
    {
        private HttpListener httpListener;
        private CancellationTokenSource tokenSource;
        public event Action<HttpListenerContext> OnRequest;

        public async void Start(int port)
        {
            httpListener = new HttpListener();
            var uri = $"http://*:{port}/";
            httpListener.Prefixes.Add(uri);
            tokenSource = new CancellationTokenSource();
            var token = tokenSource.Token;
            await ToOtherThread;
            httpListener.Start();
            UnityEngine.Debug.Log($"{nameof(HttpServer)}: Server Started, http://{GetLocalIPAddress()}:{port}");
            while (true)
            {
                try
                {
                    token.ThrowIfCancellationRequested();
                    var context = await httpListener.GetContextAsync();
                    OnRequest?.Invoke(context);
                }
                catch (Exception e)
                {
                    if (e is OperationCanceledException || e is ObjectDisposedException)
                    {
                        UnityEngine.Debug.Log($"{nameof(HttpServer)}: Server Stoped !");
                        break;
                    }
                }
            }
        }

        public void Stop()
        {
            tokenSource.Cancel();
            httpListener.Stop();
        }

        // 获取本机ip
        private string GetLocalIPAddress() 
        {
            var host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (var ip in host.AddressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            throw new Exception("No network adapters with an IPv4 address in the system!");
        }
    }
}

我可能发现问题了,在下载文件时,突然中断,如果下载逻辑没有及时 dispose掉,会有几率会导致 Server 端口占用的问题。
可能这个跟 Server 没太多关系,跟 Client 下载逻辑倒是有些关系。
我就头脑风暴一下,大胆说说了哈。