Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 调用WebRequest.create_C#_Httpwebrequest - Fatal编程技术网

C# 调用WebRequest.create

C# 调用WebRequest.create,c#,httpwebrequest,C#,Httpwebrequest,我每100毫秒调用一次下面的代码 private void First_Request() { Console.WriteLine("Connection Request"); var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method =

我每100毫秒调用一次下面的代码

private void First_Request()
{
    Console.WriteLine("Connection Request");

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER); 

    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    httpWebRequest.KeepAlive = true;
    MAC = GetMacAddress().ToString();  

    string json = new JavaScriptSerializer().Serialize(new
    {
        id = ID,
        macaddress = MAC
    });


    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var result = streamReader.ReadToEnd();
        var result_header = httpResponse.Headers;

        string cookie = httpResponse.GetResponseHeader("Set-Cookie");

        if (result.Contains("true"))
        {
            ConnectionIs = true;
        }
        else if (result.Contains("false"))
        {
            ConnectionIs = false;
        }
    }
}
我想知道连接是否会断开,然后在线路断开时重新连接

var httpWebRequest = (HttpWebRequest)WebRequest.Create(LOGIN_SERVER); 
每100ms调用一次,以向服务器发送ID和MAC地址

如果连接丢失,我该如何保持连接


或者有没有替代WebRequest的方法。创建?

HttpWebRequest使用连接池发出请求。连接和断开连接的是此池中的连接。Web请求然后从池中借用连接。因此,当var httpWebRequest=(httpWebRequest)WebRequest.Create(LOGIN_SERVER)时,它会断开连接;再次调用,然后通过以下代码再次连接。我说得对吗?我想要一个不会与服务器断开连接的结果。任何建议都会非常有用如果你想要一个连续的连接,你可能想要打开一个
套接字
。如果你真的想看看发生了什么,使用一个类似fiddler或wireshark的嗅探器。嗅探器将向您显示http数据包以及各个TCP数据包。在TCP中,您将看到连接何时打开和关闭。我相信TCP将一直保持打开状态,直到WebRequest关闭。另外,请相信创建会打开一个新的连接。这相当于有两个IE应用程序指向同一个URL。如果你在一个IE上的URL上运行一个应用程序,那么第二个IE将不会运行该应用程序。谢谢你的回答。现在我知道它正在建立新的联系,所以我正在寻找新的方法来解决它。谢谢你的推荐。它给了我一个使用cURL的新想法。如果它不工作,我可能会使用插座。谢谢你们。祝你有美好的一天。