问题
I'm trying to connect to a StreamSocketListener in my Windows 10 app. This is working if the client socket is inside the same app. But if I try to connect from another application (e.g. Putty) it doesn't work. After a few seconds putty says "Network Error: Connection Refused".
Here is my sample code:
public sealed partial class MainPage : Page
{
private StreamSocketListener listener;
public MainPage()
{
this.InitializeComponent();
listener = new StreamSocketListener();
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.BindServiceNameAsync("12345").AsTask().Wait();
}
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.WriteLine("new connection");
string message = "Hello World!";
using (var dw = new DataWriter(args.Socket.OutputStream))
{
dw.WriteString(message);
await dw.StoreAsync();
dw.DetachStream();
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
// Test connection
var serverHost = new HostName("localhost");
var socket = new StreamSocket();
await socket.ConnectAsync(serverHost, "12345");
using (var dr = new DataReader(socket.InputStream))
{
dr.InputStreamOptions = InputStreamOptions.Partial;
await dr.LoadAsync(12);
var input = dr.ReadString(12);
Debug.WriteLine("received: " + input);
}
}
}
In XAML i added a button to test the client connection.
In the manifest i have checked "Internet (Client)", "Internet (Client & Server)" and "Private Networks (Client & Server)".
EDIT: I'm trying to connect on the same computer. Firewall is deactivated.
回答1:
You cannot connect to a StreamSocketListener
from another app or process running in the same computer, not even with a loopback exemption. You will need to run the client in a different machine.
回答2:
You can connect to a localhost UWP server app only if you disable the windows firewall (via the control panel) before starting the app, and then quit the firewall service ("net stop MpsSvc", from elevated command prompt) after the app has been started. Loopbackexemption doesn't enable connections to UWP apps, only from UWP apps, in my experience at least...
regards
来源:https://stackoverflow.com/questions/32665847/cannot-connect-to-streamsocketlistener