Forum Xamarin Xamarin.Android

networkonmainthreadexception - help please

AlonAvivAlonAviv USMember ✭✭

Hi there,
I'm trying to do a simple android client app that connects to a windows forms server. I'm using C#.
I read all about sockets and how to do the simple socket connection which I desire to do.
I'm now dealing the exception of NetworkOnMainThread -
I tried reading about threads, async and services because I understood the general idea of the problem but couldn't make it work.
Can anyone please help me write an async method or a thread or a service that will allow me to do that connection and give a little explanation with it also?
in C# please.
Thanks a lot!


  • AlonAvivAlonAviv USMember ✭✭

    Ok, So I have succeeded running the app and server but now the client (android app) get stuck when I try to connect to the server. The code:

    Android Client:
    private async void getConnectedAsync()
    Socket socket1 = new Socket ();
    Socket server = new Socket ("", 8080);
    await socket1.ConnectAsync (server.RemoteSocketAddress);
    and on the main thread:
    Button button = FindViewById (Resource.Id.myButton);
    button.Click += delegate {

    C# Server:
    System.Net.IPEndPoint ip = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(""), 8080);
    Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp);
    listener.BeginAccept(new AsyncCallback(onClientConnect),null);

    private void onClientConnect(IAsyncResult ar)
    logTextBox.Text += "\n New Connection has been made";
    Socket accepted = (Socket)ar;

  • CheesebaronCheesebaron DKInsider, University mod

    You need to await your async method...

  • AlonAvivAlonAviv USMember ✭✭

    Thanks. I tried adding another method and make it await and also tried changing the original method to return a task so i could await for it to be finished. it is still not working.
    my methods looks like this:
    public async Task getConnectedAsync()
    Socket socket1 = new Socket ();
    Socket server = new Socket ("", 100);
    await socket1.ConnectAsync (server.RemoteSocketAddress);
    return "connected";

        public async void method()
                string result = await getConnectedAsync(); 
    • also, beside the async part, do you think there will be a problem connecting because i'm running these applications from the same computer? like an ip conflict or something?


Sign In or Register to comment.