Cannot connect to StreamSocketListener

匆匆过客 提交于 2019-12-22 09:28:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!