0
我正在通过Windows通用应用程序侦听连接,并希望通过Windows控制台应用程序连接到该应用程序。我已经完成了一些我认为应该连接的基本代码,但是我从控制台应用程序中收到了一个超时错误。如何从控制台应用程序连接到Windows通用应用程序StreamSocket?
{"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)
{
}
}
谢谢我没有意识到我无法在同一台机器上运行它们。这是为什么?它会被修复吗? –
@SethKitchen,这不是一个错误,这是设计。这受到网络隔离的限制。可能出于安全原因。 –
我读到了“注意:作为网络隔离的一部分,系统禁止通过本地环回地址(127.0.0.0)或明确指定本地IP地址在同一台机器上运行的两个UWP应用程序之间建立套接字连接(套接字或WinSock) “在https://docs.microsoft.com/en-us/windows/uwp/networking/sockets - 但为什么我不能像本地浏览器那样从非UWP应用程序连接?不要明白什么是安全问题,尤其是当他们不允许使用IP地址并至少打开一些防火墙端口时 –