简体   繁体   English

HttpWebRequest和长轮询:如何确定长轮询连接是否已建立?

[英]HttpWebRequest & Long Polling: how can I tell if a Long Polling connection has been established?

I need to make a long polling connection between my application and the server. 我需要在应用程序和服务器之间建立长轮询连接。 I am using HttpWebRequest class and it works: 我正在使用HttpWebRequest类,它可以工作:

    for (; ; )
    {
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

        request.Timeout = 100000;
        request.Method = "GET";
        request.KeepAlive = true;
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;

        var response = request.GetResponse();
        :
        : (wait for response...)
    }

I need to know whether the server is online or not. 我需要知道服务器是否在线。 If it is offline, the application needs to immediately notify the user. 如果处于脱机状态,则应用程序需要立即通知用户。 However, if the server is offline, the GetResponse() won't return any error until it has reached the timeout. 但是,如果服务器处于脱机状态,则GetResponse()在达到超时之前不会返回任何错误。

I can't reduce the timeout to say 0.1s neither because the application is supposed to sit and wait for the reply from the server. 我也不能将超时时间减少为0.1秒,因为应用程序应该坐下来等待服务器的回复。

My question is if there is any way for me to tell immediately when a connection with the server has been successfully established (without disconnecting from the server of course)? 我的问题是,是否有什么方法可以让我立即知道与服务器的连接已成功建立(当然不断开与服务器的连接)?

Please help. 请帮忙。 Thank you. 谢谢。

I finally used WebSocket instead of Long Polling, using WebSocket4Net, and it works: 我终于使用WebSocket4Net使用WebSocket而不是Long Polling,它可以工作:

WebSocket websocket = new WebSocket(url);

websocket.Opened += (sender, e) =>
{
    // successfully connected, do sth (this is what i need)
};

websocket.Error += (sender, e) =>
{
    Console.WriteLine(e.Exception.Message);
};

websocket.MessageReceived += (sender, e) =>
{
    string msg = e.Message;
};

websocket.Open();

Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM