[英]How to cancel by timeout StreamSocket in C# Universal WIndows App?
[英]How do I connect to a Windows Universal App StreamSocket from a Console Application?
我正在通過Windows Universal應用程序偵聽連接,並希望通過Windows控制台應用程序連接至該應用程序。 我已經完成了一些我認為應該連接的基本代碼,但是從控制台應用程序中收到了超時錯誤。
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.0.5:1771"}
Windows通用應用程序甚至從不進入連接接收功能。
服務器(UWP):
public async void SetupServer()
{
try
{
//Create a StreamSocketListener to start listening for TCP connections.
Windows.Networking.Sockets.StreamSocketListener socketListener = new Windows.Networking.Sockets.StreamSocketListener();
//Hook up an event handler to call when connections are received.
socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
//Get Our IP Address that we will host on.
IReadOnlyList<HostName> hosts = NetworkInformation.GetHostNames();
HostName myName = hosts[3];
//Assign our IP Address
ipTextBlock.Text = myName.DisplayName+":1771";
ipTextBlock.Foreground = new SolidColorBrush(Windows.UI.Color.FromArgb(255,0,255,0));
//Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
await socketListener.BindEndpointAsync(myName, "1771");
}
catch (Exception e)
{
//Handle exception.
}
}
客戶端(控制台應用程序):
static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
int sent;
string ip = "192.168.0.5";
int port = 1771;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ip), port);
TcpClient client = new TcpClient();
client.Connect(ipep); //**************Stalls HERE************
using (NetworkStream ns = client.GetStream())
{
using (StreamReader sr = new StreamReader(ns))
{
using (StreamWriter sw = new StreamWriter(ns))
{
sw.WriteLine("Hello!");
sw.Flush();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("Response: " + sr.ReadLine());
}
}
}
}
catch (Exception e)
{
}
}
我已經對您的代碼進行了測試,它可以很好地工作。 因此,您的代碼沒有錯。 但是我可以通過在同一台設備上運行服務器和客戶端來重現您的問題,客戶端將拋出與上面顯示的異常相同的異常。 因此,請確保您正在從另一台計算機進行連接。 我們無法從同一台計算機上運行的另一個應用程序或進程連接到uwp應用程序StreamSocketListener ,這是不允許的。 甚至沒有環回豁免。
還請確保已啟用Internet(Client&Server)
功能 。 在客戶端上,您可以成功ping服務器192.168.0.5
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.