Search code examples
c#socketssilverlightwindows-phone-8windows-phone-8-emulator

Windows phone silverlight socket HostNotFound error


I am getting HostNotFound error while trying to connect with socket in async. I am sure, that host is working. The strangest part is that all emulator starting from "8.1 u1 *" dont give such error. They connect without any problems. Only my device (htc windows phone 8s) and emulators without 8.1 getting this error. Host address 109.235.68.205 and port 6005. I am targeting 8.0 windows phone. I have no ideas how to solve it.

public string Connect(string hostName, int portNumber)
    {

        string result = string.Empty;

        // Create DnsEndPoint. The hostName and port are passed in to this method.
        DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);

        // Create a stream-based, TCP socket using the InterNetwork Address Family. 
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Create a SocketAsyncEventArgs object to be used in the connection request
        SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
        socketEventArg.RemoteEndPoint = hostEntry;


        // Inline event handler for the Completed event.
        // Note: This event handler was implemented inline in order to make this method self-contained.
        socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
        {
            // Retrieve the result of this request
            result = e.SocketError.ToString();

            // Signal that the request is complete, unblocking the UI thread
            _clientDone.Set();
            if(OnConnect != null)
                OnConnect(true, new ConnectionEventArgs() { Response = result });
        });



        // Sets the state of the event to nonsignaled, causing threads to block
        _clientDone.Reset();

        // Make an asynchronous Connect request over the socket
        _socket.ConnectAsync(socketEventArg);

        // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
        // If no response comes back within this time then proceed
        _clientDone.WaitOne(TIMEOUT_MILLISECONDS);

        return result;
    }

Solution

  • I was able to successfully run your code on the Windows Phone 8 emulators targeting one of my network machines.

    The socket.ConnectAsync call is already an Async request that wouldn't block your UI so I don't think you require the manual steps to manage thread synchronization.

    But if you insist on this implementation, you can replace the DnsEndPoint with IPEndpoint in your code.

    IPEndPoint hostEntry = new IPEndPoint(IPAddress.Parse(hostName), portNumber);

    Hope this helps.