首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpListener的使用

HttpListener的使用
EN

Stack Overflow用户
提问于 2014-10-02 16:58:24
回答 2查看 37.7K关注 0票数 9

我有下面的HTTP listener方法,这很大程度上受到了MSDN使用HttpListener类示例的启发。我是一个编程新手,我不确定从这里到哪里去从我的Main()初始化它。有什么建议吗?

代码语言:javascript
复制
 public static void HttpListener(string[] prefixes)
    {
        if (prefixes == null || prefixes.Length == 0)
            throw new ArgumentException("Prefixes needed");

        HttpListener listener = new HttpListener();

        foreach (string s in prefixes)
        {
            listener.Prefixes.Add(s);
        }
        listener.Start();
        Console.WriteLine("Listening..");

        HttpListenerContext context = listener.GetContext();
        HttpListenerRequest request = context.Request;
        HttpListenerResponse response = context.Response;

        string responseString = "<HTML><BODY> Test </BODY></HTML>";
        byte[] buffer = Encoding.UTF8.GetBytes(responseString);

        response.ContentLength64 = buffer.Length;
        Stream output = response.OutputStream;
        output.Write(buffer, 0, buffer.Length);

        output.Close();
        listener.Stop();
    }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-02 17:54:01

您似乎已经删除了MSDN HttpListener Class页面上提到的注释:

// URI前缀必填,例如"http://contoso.com:8080/index/“。

所以就这么叫吧:

代码语言:javascript
复制
public static void Main(string[] args)
{
    HttpListener(new[] { "http://localhost/" });
}

但请注意,此示例将仅处理一个请求,然后退出。如果您的后续问题是“如何让它处理多个请求?”,请参阅Handling multiple requests with C# HttpListener

票数 14
EN

Stack Overflow用户

发布于 2017-10-22 22:06:38

你可以这样做:

代码语言:javascript
复制
   public void ListenTraces()
    {
        httpListener.Prefixes.Add(PORT_HOST);
        try
        {
            httpListener.Start();
        }
        catch (HttpListenerException hlex)
        {
            log.Warn("Can't start the agent to listen transaction" + hlex);
            return;
        }
        log.Info("Now ready to receive traces...");
        while (true)
        {
            var context = httpListener.GetContext(); // get te context 

            log.Info("New trace connexion incoming");
           Console.WriteLine(context.SomethingYouWant);
        }
    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26157475

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档