为什么我会“无法连接到远程服务器”?

时间:2014-03-10 17:09:04

标签: httpwebrequest compact-framework streamreader httpwebresponse motorola

这个错误的消息是我解决“NotSupportedException”后得到的下一个消息here

我甚至没有达到服务器代码中的断点(在应该调用的方法的第一行上设置)。

这是相关的服务器代码:

[Route("api/PlatypusItems/PostArgsAndXMLFileAsStr")]
public async void PostArgsAndXMLFileAsStr([FromBody] string stringifiedXML, string serialNum, string siteNum)
{
    string beginningInvoiceNum = string.Empty; // <= Breakpoint on this line
    string endingInvoiceNum = string.Empty;

    XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
        . . .

客户端(掌上电脑,Compact Framework)代码:

private void menuItem4_Click(object sender, EventArgs e)
{
    GetAndSendXMLFiles("LocateNLaunch"); // There is a "LocateNLaunch.xml" file
}

private void GetAndSendXMLFiles(string fileType)
{
    string serNum = User.getSerialNo();
    string siteNum = User.getSiteNo();
    if (serNum.Length == 0)
    {
        serNum = "8675309";
    }
    if (siteNum.Length == 0)
    {
        siteNum = "03";
    }
    string uri = string.Format("http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum={0}&siteNum={1}", serNum, siteNum);
    List<String> XMLFiles = HHSUtils.GetXMLFiles(fileType, @"\");
    MessageBox.Show(XMLFiles.Count.ToString());
    foreach (string fullXMLFilePath in XMLFiles)
    {
        MessageBox.Show(fullXMLFilePath);
        RESTfulMethods.SendXMLFile(fullXMLFilePath, uri, 500);
    }
}

public static string SendXMLFile(string xmlFilepath, string uri, int timeout) // timeout should be 500
{
    MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));
    MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

    request.KeepAlive = false;
    request.ProtocolVersion = HttpVersion.Version10;

    request.Method = "POST";

    StringBuilder sb = new StringBuilder();
    using (StreamReader sr = new StreamReader(xmlFilepath))
    {
        String line;
        while ((line = sr.ReadLine()) != null)
        {
            sb.AppendLine(line);
        }
        byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());

        if (timeout < 0)
        {
            request.ReadWriteTimeout = timeout;
            request.Timeout = timeout;
        }

        request.ContentLength = postBytes.Length;
        request.KeepAlive = false;

        request.ContentType = "application/xml";

        try
        {
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                return response.ToString();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("SendXMLFile exception " + ex.Message);
            request.Abort();
            return string.Empty;
        }
    }
}

运行此代码,我从客户端看到以下“调试字符串”:

0) "1" (from MessageBox.Show(XMLFiles.Count.ToString());)

1) "\Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(fullXMLFilePath);)

2) "In SendXMLFile() - xmlFilePath == \Program Files\LocateNLaunch\LocateNLaunch.xml" (from MessageBox.Show(string.Format("In SendXMLFile() - xmlFilepath == {0}", xmlFilepath));)

3) "In SendXMLFile() - uri == http://localhost:28642/api/PlatypusItems/PostArgsAndXMLFileAsStr?serialNum=8675309&siteNum=03" (from MessageBox.Show(string.Format("In SendXMLFile() - uri == {0}", uri));)

- and then this one from somewhere:

4) "SendXMLFile exception Unable to connect to the remote server"...
So what could be causing this inability to connect?

更新

同样的事情(“无法连接到远程服务器”)发生在这段代码中(不同的操作,但也来自尝试连接到Web API服务器应用程序的WindowsCE / Compact Framework /掌上电脑应用程序):

private void menuItem3_Click(object sender, EventArgs e)
{
    string serNum = User.getSerialNo();
    if (serNum.Length == 0)
    {
        serNum = "8675309";
    }
    string clientVer = 
        HHSUtils.GetFileVersion(@"\Application\sscs\vsd_setup.dll");
    if (clientVer.Contains("Win32Exception")) 
    {
        clientVer = "0.0.0.0";
    }

    MessageBox.Show(string.Format("After call to GetFileVersion(), serial num == {0}; 
clientVer == {1}", serNum, clientVer));
    string uri = 
       string.Format("http://localhost:28642/api/FileTransfer/GetHHSetupUpdate?
       serialNum={0}&clientVersion={1}", serNum, clientVer);
    RESTfulMethods.DownloadNewerVersionOfHHSetup(uri);
}

public static void DownloadNewerVersionOfHHSetup(string uri)
{
    string dateElements = DateTime.Now.ToString("yyyyMMddHHmmssfff", 
        CultureInfo.InvariantCulture);
    var outputFileName = string.Format("HHSetup_{0}.exe", dateElements);
    try
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        string statusCode = webResponse.StatusCode.ToString();
        if (statusCode == "NoContent")
        {
            MessageBox.Show("You already have the newest available version.");
        }
        else
        {
            var responseStream = webResponse.GetResponseStream();
            using (Stream file = File.Create(outputFileName))
            {
                CopyStream(responseStream, file);
                MessageBox.Show(string.Format("New version downloaded to {0}",  
                    outputFileName));
            }
        }
    }
    catch (WebException webex)
    {
        MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
    }
}

//我在menuItem3_Click()处理程序中看到“在调用GetFileVersion()之后”消息,但在DownloadNewerVersionOfHHSetup()中看到“DownloadNewerVersionOfHHSetup:无法连接到远程服务器”

是的,服务器应用程序 正在运行。

更新2

以下是我在“简化它”之前测试过的代码(对其进行改造,使其尽可能与此工作测试代码相似,但对于Compact Framework来说可能并不多):

客户代码:

DownloadTheFile(textBoxFinalURI.Text); // with textBoxFinalURI.Text being 
    "http://localhost:28642/api/FileTransfer/GetUpdatedHHSetup?
    serialNum=8675309&clientVersion=1.3.3.3" and the file on the server being 
    version 1.4.0.15

private void DownloadTheFile(string uri)
{
    var outputFileName = "Whatever.exe";
    try
    {
        var webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var webResponse = (HttpWebResponse)webRequest.GetResponse();
        string statusCode = webResponse.StatusCode.ToString();
        if (statusCode == "NoContent")
        {
            MessageBox.Show("You already have the newest available version.");
        }
        else
        {
            var responseStream = webResponse.GetResponseStream();
            using (Stream file = File.Create(outputFileName))
            {
                CopyStream(responseStream, file);
                MessageBox.Show(string.Format("New version downloaded to {0}", 
                    outputFileName));
            }
        }
    }
    catch (WebException webex)
    {
        MessageBox.Show(webex.Message);
    }
}

服务器代码:

public HttpResponseMessage GetHHSetupUpdate(string serialNum, string clientVersion)
{
    HttpResponseMessage result;
    string filePath = GetAvailableUpdateForCustomer(serialNum);
    FileVersionInfo currentVersion = FileVersionInfo.GetVersionInfo(filePath);
    if (!ServerFileIsNewer(clientVersion, currentVersion))
    {
        result = new HttpResponseMessage(HttpStatusCode.NoContent);
    }
    else
    {
        result = new HttpResponseMessage(HttpStatusCode.OK);
        var stream = new FileStream(filePath, FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType =
            new MediaTypeHeaderValue("application/octet-stream");
    }
    return result;
}

private string GetAvailableUpdateForCustomer(string serialNum)
{
    if (serialNum == "8675309")
    {
        return HostingEnvironment.MapPath(@"~\App_Data\HHSetup.exe");
    }
    else
    {
        return HostingEnvironment.MapPath(@"~\App_Data\HDP.exe");
    }
}

// clientFileVersion is expected to be something like "1.4.0.15"
private bool ServerFileIsNewer(string clientFileVersion, FileVersionInfo serverFile)
{
    Version client = new Version(clientFileVersion);
    Version server = new Version(string.Format("{0}.{1}.{2}.{3}", 
        serverFile.FileMajorPart, serverFile.FileMinorPart,    
        serverFile.FileBuildPart, serverFile.FilePrivatePart));
    return server > client;
}

...此代码工作正常(服务器代码相同;客户端代码已被“翻新”)

由于Compact Framework / Windows CE的限制,我无法按原样使用代码。正如这篇文章的标题所表明的那样,我甚至无法从那里连接到服务器。可能吗?如果是这样,我的客户端代码需要更改什么(不是Update 2中的客户端代码,它在较新版本的.NET中运行,但之前显示的客户端代码)?

与其他方法类似的故事也回归“无法连接到远程服务器” - 它在测试应用程序中运行的“现代”代码中运行良好,但是一旦它被改装(更好的词比重构时更好)减少“Compact Compacterize代码”。

更新3

我试图通过下面的代码从旧错误信息中获取更多信息(旧行注释掉),但这会“奖励”我而不是NullReferenceException:

catch (WebException webex)
{
    //MessageBox.Show("DownloadNewerVersionOfHHSetup: " + webex.Message);
    string msg = webex.Message;
    string innerEx = webex.InnerException.ToString();
    string resp = webex.Response.ToString();
    string stackTrace = webex.StackTrace;
    string status = webex.Status.ToString();
    MessageBox.Show(
        string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
}

更新4

当我继续获得NRE时,我逐一评论了每一条后续行,直到我现在有了这个:

//string innerEx = webex.InnerException.ToString();
//string resp = webex.Response.ToString();
//string stackTrace = webex.StackTrace;
string status = webex.Status.ToString();
MessageBox.Show(
    //string.Format("Message: {0}; Inner Exception: {1}; Response: {2}; Stack Trace: {3}; Status: {4}", msg, innerEx, resp, stackTrace, status));
    //string.Format("Message: {0}; Response: {1}; Stack Trace: {2}; Status: {3}", msg, resp, stackTrace, status));
    //string.Format("Message: {0}; Stack Trace: {1}; Status: {2}", msg, stackTrace, status));
    string.Format("Message: {0}; Status: {1}", msg, status));

...但我得到的只是“ConnectFailure”的状态(我已经知道了)。

更新5

这在没有NRE的情况下运行:

string msg = webex.Message;
string innerEx = webex.InnerException.ToString();
string status = webex.Status.ToString();
MessageBox.Show(string.Format("Message: {0}; Status: {1}; inner Ex: {2}", msg, status, innerEx));

这就是我所看到的:

enter image description here

那么为什么服务器会主动拒绝连接?

顺便说一句,尽管如此,我还是要确定这个问题,或者在事实*之后确认回答者,还会得到一笔甚至可能让Long John Silver和Perro-Negro的眼睛闪烁着光芒的奖励(关心他们的geekCoin,那个是)。

  • 导致逮捕和驱逐这个错误的事实。

PSYCHE!我改变主意/在赏金上发生了叛变=&gt;相反,会发生here

更新6

这也(使用服务器机器的“原始”IP地址)给了我一个NRE:

string uri = string.Format("http://192.168.125.50:28642/api/FileTransfer/GetHHSetupUpdate?serialNum={0}&clientVersion={1}", serNum, clientVer);

...使用机器的“友好名称”(“Platypus”)代替IP地址。

1 个答案:

答案 0 :(得分:1)

我在这里看到的一个大问题是你有[{1}}作为你的地址。那是绝对错误的。 localhost实际上意味着“在我正在运行的同一台机器上”,所以除非你以某种方式设法让你的Windows CE设备上运行异步.NET 4.0 Web服务并且你的服务器代码在那里运行,那么这肯定不是你想要的。

如果你在模拟器上运行,它仍然是错误的。出于所有意图和目的,模拟器是一台单独的机器。

您必须使用运行该Web服务的服务器/ PC的地址。它必须是可路由的地址,这意味着如果您通过USB连接,那么它可能是localhost而不是IP地址(它可以解析为私有地址,但名称更容易记住)。