为什么会出现“无法连接到远程服务器”的提示?

编程入门 行业动态 更新时间:2024-10-25 14:32:44
本文介绍了为什么会出现“无法连接到远程服务器”的提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此错误消息是我在解决 NotSupportedException后得到的下一个错误消息,。

UPDATE 6

这也(使用服务器计算机的原始 IP地址)为我提供了NRE:

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

...就像使用机器的友好名称( Platypus)一样

解决方案

我在这里看到的最大问题是您拥有 localhost 作为您的地址。绝对是错的 localhost 实际上是指与我正在运行的同一台计算机上,因此,除非您设法以某种方式设法使异步.NET 4.0 Web服务在Windows CE上运行设备,并且服务器代码正在此处运行,那么这肯定不是您想要的。

如果您在模拟器上运行,那仍然是错误的。出于所有目的和目的,模拟器都是一台单独的计算机。

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

This err msg is the next one I get after resolving "NotSupportedException" as noted here

I don't even reach the break point in the server code (set on the first line of the method that should be getting called).

This is the relevant server code:

[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()); . . .

And the client (handheld, Compact Framework) code:

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("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; } } }

Running this code, I see from the client the following "debug strings":

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 == 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?

UPDATE

The same thing ("Unable to Connect to the Remote Server") happens with this code (different operation, but also from the WindowsCE/Compact Framework/handheld app that tries to connect to the Web API server app):

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("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); } }

// I see the "After call to GetFileVersion()" message in menuItem3_Click() handler, but then "DownloadNewerVersionOfHHSetup: Unable to Connect to the Remote Server" in DownloadNewerVersionOfHHSetup()

And yes, the server app is running.

UPDATE 2

Here is the code that I tested prior to "dumbing it down" (retrofitting it, making it as similar as possible to this working test code, yet that may not be saying much) for Compact Framework:

Client code:

DownloadTheFile(textBoxFinalURI.Text); // with textBoxFinalURI.Text being "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); } }

Server code:

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; }

... This code works fine (server code is the same; the client code has been "retrofied")

I can't use the code as-is because of the limitations of Compact Framework / Windows CE. As the title of this post makes clear, I'm not even able to connect to the server from there yet. Is it possible? If so, what needs to change in my client code (not the client code in Update 2, which works in newer versions of .NET, but the client code shown prior to there)?

It's a similar story with the other method that is also returning "Unable to connect to the remote server" - it works fine in "modern" code running in a test app, but once it's retrofitted (better word than refactored when "dumbing down" to Compact Frameworkerize the code).

UPDATE 3

I tried to get more info from the err msg with the code below (old line commented out), but this "rewards" me instead with a 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)); }

UPDATE 4

As I continued to get NREs, I commented out each subsequent line, one-by-one, until I now have this that runs:

//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));

...but all I get from it is Status of "ConnectFailure" (I already knew that).

UPDATE 5

This runs without an 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));

And this is what I see:

So why would the server actively refuse the connection?

BTW, ASAP I'm going to bountify this question, or will bountify the answerer after the fact*, with a bounty that would make even Long John Silver and Perro-Negro's eyes glimmer and gleam (cared they for geekCoin, that is).

  • For facts leading to the arrest and eviction of this bug.

PSYCHE! I changed my mind/there's been a mutiny on the bounty => the bountification will happen here instead.

UPDATE 6

This also (using the "raw" IP Address of the server machine) gives me an NRE:

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

...as does using the "friendly name" ("Platypus") of the machine in place of the IP Address.

解决方案

The large problem I see here is the fact that you have localhost as your address. That's absolutely wrong. localhost means, effectively, "on the same machine as I am running" so unless you've somehow managed to get a async .NET 4.0 web service to run on your Windows CE device and your server code is running there, then this is most certainly not what you want.

If you're running on an emulator, it's still wrong. The emulator is, for all intents and purposes, a separate machine.

You must use the address of the server/PC where that web service is running. It must be a routable address, meaning if you're connected over USB then it's probably ppp_peer and not an IP address (well it resolves to a private address, but the name is easier to remember).

更多推荐

为什么会出现“无法连接到远程服务器”的提示?

本文发布于:2023-10-15 01:14:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1492810.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:连接到   提示   服务器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!