locked
Can't connect to a StreamSocketListener from a Windows Phone 7.1 App

    Question

  • Hello,

    I have an application running on a Windows 8.1 and another application running on a Windows Phone and I want to send messages from the phone to the PC via a socket. In the phone I have this code:

    SocketClient.cs

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

    MainPage.xaml.cs

            private void Connect_Click(object sender, RoutedEventArgs e)
            {
                int portNum;
                string result;
                
                try
                {
                    portNum = Convert.ToInt32(PortTextBox.Text);
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid Port Number");
                }
    
                try
                {
                    IPAddress ipAddress = IPAddress.Parse(IPTextBox.Text);
                    portNum = Convert.ToInt32(PortTextBox.Text);
    
                    result = client.Connect(ipAddress, portNum);
                    MessageBox.Show(result);
                }
                catch (ArgumentNullException)
                {
                    MessageBox.Show("Enter an IP Address.");
                }
                catch (FormatException)
                {
                    MessageBox.Show("Invalid IP Address.");
                }
            }

    And on the PC I have this one running:

    MainPage.xaml.cs

    private async void StartListener_Click(object sender, RoutedEventArgs e) { if (listening) { NotifyUser("The application is already connected.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(PortBox.Text)) { NotifyUser("Please fill the parameter boxes.", NotifyType.ErrorMessage); return; } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; try { await listener.BindServiceNameAsync(PortBox.Text); listening = true; NotifyUser("Listening", NotifyType.StatusMessage); } catch (Exception exception) { if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } NotifyUser("Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }

    private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
            {
                DataReader reader = new DataReader(args.Socket.InputStream);
                try
                {
                    while (true)
                    {
                        // Read first 4 bytes (length of the subsequent string).
                        uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                        if (sizeFieldCount != sizeof(uint))
                        {
                            // The underlying socket was closed before we were able to read the whole data.
                            return;
                        }

                        // Read the string.
                        uint stringLength = reader.ReadUInt32();
                        uint actualStringLength = await reader.LoadAsync(stringLength);
                        if (stringLength != actualStringLength)
                        {
                            // The underlying socket was closed before we were able to read the whole data.
                            return;
                        }

                        // Display the string on the screen. The event is invoked on a non-UI thread, so we need to marshal
                        // the text back to the UI thread.
                        NotifyUserFromAsyncThread(String.Format("Received data: \"{0}\"", reader.ReadString(actualStringLength)), NotifyType.StatusMessage);
                    }
                }
                catch (Exception exception)
                {
                    // If this is an unknown status it means that the error is fatal and retry will likely fail.
                    if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                    {
                        throw;
                    }

                    NotifyUserFromAsyncThread("Read stream failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }

    And it happens that I can't make a connection between them. Any thoughts?



    Monday, April 14, 2014 9:52 PM

Answers

  • The best way to troubleshoot this issue is to collect a network trace on your Windows 8.1 machine and watch the incoming network traffic to see if there is a TCP-SYN attempt from the Phone. If you see the TCP-SYN from the phone on the port where your StreamSocketListener is running then you probably need to open the firewall to allow the connection. If you do not even see the TCP-SYN, then the problem lies on the Phone side.

    You can collect a network trace on your Windows machine by running a tool called Microsoft Network Monitor: http://www.microsoft.com/en-us/download/details.aspx?id=4865


    Windows Store Developer Solutions, follow us on Twitter: @WSDevSol|| Want more solutions? See our blog

    • Marked as answer by lucasmoraes90 Monday, April 14, 2014 11:50 PM
    Monday, April 14, 2014 10:34 PM
    Moderator
  • What is the IP address you are using ?  I am mostly wondering if the phone is connected veto the internet via its cell phone and the computer has an IP address that starts with 192.168. Which is a local network IP that a phone on cell network would not be able to because it is a different network
    • Marked as answer by lucasmoraes90 Monday, April 14, 2014 11:50 PM
    Monday, April 14, 2014 10:35 PM

All replies

  • The best way to troubleshoot this issue is to collect a network trace on your Windows 8.1 machine and watch the incoming network traffic to see if there is a TCP-SYN attempt from the Phone. If you see the TCP-SYN from the phone on the port where your StreamSocketListener is running then you probably need to open the firewall to allow the connection. If you do not even see the TCP-SYN, then the problem lies on the Phone side.

    You can collect a network trace on your Windows machine by running a tool called Microsoft Network Monitor: http://www.microsoft.com/en-us/download/details.aspx?id=4865


    Windows Store Developer Solutions, follow us on Twitter: @WSDevSol|| Want more solutions? See our blog

    • Marked as answer by lucasmoraes90 Monday, April 14, 2014 11:50 PM
    Monday, April 14, 2014 10:34 PM
    Moderator
  • What is the IP address you are using ?  I am mostly wondering if the phone is connected veto the internet via its cell phone and the computer has an IP address that starts with 192.168. Which is a local network IP that a phone on cell network would not be able to because it is a different network
    • Marked as answer by lucasmoraes90 Monday, April 14, 2014 11:50 PM
    Monday, April 14, 2014 10:35 PM
  • Thanks for the reply!

    It seems that the problem is indeed on the phone side, because I could find the TCP attempt at all. At least I know where to focus!

    Monday, April 14, 2014 11:33 PM
  • Actually, both my PC and the phone are connected to my university's network. Their IP are not 192.168 something.
    Monday, April 14, 2014 11:35 PM