locked
Can't connect to a StreamSocketListener

    Question

  • I built an Windows 8.1 application that creates a StreamSocketListener on a specific port, but I can not make any connections to it. I run the netstat -a command and it appears that the program is listening my IP address, I've allowed that port on Windows Firewall and set the Internet (Client and Server) and Private Networks capabilities. Is there any other thing that I have to do?

    private async void StartListener(object sender, RoutedEventArgs e)
            {
                var localHostList = NetworkInformation.GetHostNames();
                foreach (HostName hostName in localHostList)
                {
                    if (HostName.Compare (hostName.ToString(), "0.0.0.0") > 0)
                    {
                        localHostName = hostName;
                    }
                }
    
                listener.ConnectionReceived += OnConnection;
    
                try
                {
                    await listener.BindEndpointAsync(localHostName, PORT_LISTEN);
                    NotifyUser(">> Listening to " + localHostName.ToString() + " : " + listener.Information.LocalPort, NotifyType.StatusMessage);
                }
                catch (Exception exception)
                {
                    if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                    {
                        throw;
                    }
    
                    NotifyUser("!! Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }
    
            /// <summary>
            /// Invoked once a connection is accepted by StreamSocketListener.
            /// </summary>
            /// <param name="listener">The listener that accepted the connection.</param>
            /// <param name="args">Parameters associated with the accepted connection.</param>
            private async void OnConnection(StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args)
            {
                DataReader reader = new DataReader(args.Socket.InputStream);
                try
                {
                    while (true)
                    {
                        uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                        if (sizeFieldCount != sizeof(uint))
                        {
                            return;
                        }
    
                        uint stringLength = reader.ReadUInt32();
                        uint actualStringLength = await reader.LoadAsync(stringLength);
                        if (stringLength != actualStringLength)
                        {
                            return;
                        }
    
                        NotifyUserFromAsyncThread(String.Format("<< Received data: \"{0}\"", reader.ReadString(actualStringLength)), NotifyType.MsgMessage);
                        sReceived = reader.ReadString(actualStringLength);
                        ProcessMessage(sReceived);
                    }
                }
                catch (Exception exception)
                {
                    if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                    {
                        throw;
                    }
    
                    NotifyUserFromAsyncThread(">> Read stream failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }

    Friday, April 18, 2014 11:09 AM

All replies

  • Have you tested from both local and remote?

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, April 18, 2014 12:34 PM
    Moderator
  • As local you mean: create a StreamSocket inside the app and try to connect? I only tried to connect from a TCP Client phone application.
    Friday, April 18, 2014 12:53 PM
  • Meaning did you try to connect to the app from another app or application that resides on the same machine, using 127.0.0.1 as the IP address, and did you try to connect from another remote machine? It sounds like you tried to connect from a phone - how about trying from another Windows machine?

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, April 18, 2014 1:17 PM
    Moderator
  • I will try that, but why it would not connect to the phone is the main problem, as I want to connect them. The code in the phone is:

    public string Connect()
            {
                string result = string.Empty;
    
                IPEndPoint hostEntry = new IPEndPoint(IPAddress.Any, LISTEN_PORT);
    
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
                {
                    result = e.SocketError.ToString();
                    clientDoneEvent.Set();
                });
                socketEventArg.RemoteEndPoint = hostEntry;
                socketEventArg.UserToken = socket;
    
                clientDoneEvent.Reset();
    
                socket.ConnectAsync(socketEventArg);
    
                clientDoneEvent.WaitOne(TIMEOUT_MILLISECONDS);
    
                return result;
            }

    Friday, April 18, 2014 1:47 PM
  • Sure, but you need to isolate the cause first.

    Matt Small - Microsoft Escalation Engineer - Forum Moderator
    If my reply answers your question, please mark this post as answered.

    NOTE: If I ask for code, please provide something that I can drop directly into a project and run (including XAML), or an actual application project. I'm trying to help a lot of people, so I don't have time to figure out weird snippets with undefined objects and unknown namespaces.

    Friday, April 18, 2014 2:07 PM
    Moderator
  • Alright, I used another application on my computer, using the IP "127.0.0.1" as the local IP address and tried to connect to my listener. It could not connect and the error was "Network Is Unreachable". Any ideas?
    Monday, April 21, 2014 8:12 PM