关闭 HttpListener 失败

问题描述

我有一个 WPF 应用程序,其中包含用于播放视频的 MediaElement,它还运行 HttpServer,它将视频文件的响应作为字节数组返回。 HttpServer 在 localhost:1234 上运行,MediaElement.source 指向 localhost:1234。 该应用程序播放视频,但是如果我在没有事先关闭应用程序的情况下重新打开文件以再次播放相同或另一个文件,则无法重新播放。错误很明显:1234端口上的httplistener被占用了。所以最好的选择是关闭监听器并重新打开它。但是它不起作用。任何想法如何正确关闭侦听器?

这里另一个有趣的时刻是文件被读取并返回 2 次而不是 1 次,不知道为什么。但是,如果我将 while 循环替换为 for(int i=0; i

代码如下:

string videoServerUrl = "http://localhost:1234/";
public HttpListener listener;

public async Task HandleIncomingConnections(string fileName)
{
    bool runServer = true;
    
    while (runServer)             
    {
        HttpListenerContext ctx = await listener.GetContextAsync();

        HttpListenerRequest req = ctx.Request;
        HttpListenerResponse resp = ctx.Response;

        if (req.HttpMethod == "POST")  
        {
            runServer = false;
            resp.Close();
            return;
        }

        var bytesRead = File.ReadAllBytes(fileName);
        resp.ContentLength64 = bytesRead.Length;
        await resp.OutputStream.WriteAsync(bytesRead,bytesRead.Length);

        resp.Close();
    }
}

private void RunServer(string fileName)
{
     listener = new HttpListener();
     listener.Prefixes.Add(videoServerUrl);
     listener.Start();
         
     Task listenTask = HandleIncomingConnections(fileName);
     listenTask.GetAwaiter().GetResult();

     listener.Close();     
}


private async void Button_Click(object sender,RoutedEventArgs e)
{
    try
    {    
        OpenFileDialog openFileDialog = new OpenFileDialog();
        if (openFileDialog.ShowDialog() == true)
        {                    
            string videoFileName = openFileDialog.FileName;
            player.LoadedBehavior = MediaState.Manual;
            player.source = new Uri(videoServerUrl.ToString(),UriKind.RelativeOrAbsolute);
            player.Play();

            Task.Run(() => RunServer(videoFileName)).ConfigureAwait(false);
       
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...