Unable to display the messages received on UI when using System.net.Sockets connection

Hi,

I am new to xamarin.forms. I want to build an xamarin forms app that can receive messages using System.net.Sockets. My problem is that i am able to receive messages but unable to make the messages displaying on the UI.

I am using dependency service, so I implemented the socket method on every platform specifically, this is my socket receive method in the android project. I am trying to use messaging center to send the data from android project to the PCL project. IResource is a class i defined in pcl.

class SocketConnection : ISocket
{
Socket sSocket;
Socket serverSocket;

 public void ReceiveMessage()
    {
        Int32 port = 7777;


        IPAddress address = IPAddress.Parse("192.168.2.100");
        IPEndPoint ipe = new IPEndPoint(address, port);

        sSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sSocket.Bind(ipe);
        sSocket.Listen(0);

        //receive message
        serverSocket = sSocket.Accept();
        Console.WriteLine("connection succeeded");

        while (true)
           {
               byte[] recByte = new byte[4096];
             int bytes = serverSocket.Receive(recByte, recByte.Length, 0);
                IResource.data1+=Encoding.ASCII.GetString(recByte, 0, bytes);

             MessagingCenter.Send<SocketConnection, string>(this,"new Messages",IResource.data1);

            Console.WriteLine("client: " + IResource.data1);

               //send message
               if (IResource.data1.Equals("exit"))
               {
                   break;
               }
           }

         serverSocket.Close();
         sSocket.Close();

    }

}

And in my pcl project, I have a button, when this button is clicked it will use call the ReceiveMessage() method. And I also used the messaging center to receive the messages and display it on UI, but it didn't work out. this is the method for the button click. does anyone know where is the problem, is that i am not using messaging center correctly, or something else. plus: when the button is clicked, the UI becomes unresponsive, should I use asynchronous programming? and how?
Thanks in advance!

private async void Yes_Clicked(object sender, EventArgs e)
{

        DependencyService.Get<ISocket>().ReceiveMessage();  
        Debug.WriteLine("Messaging center will be working ");
        MessagingCenter.Subscribe<ISocket,string>(this,"new Messages", (socket, data) =>
        {
            Device.BeginInvokeOnMainThread(() => {
                editor.IsVisible = true;
                editor.Text = data;

            });
        });

}

Sign In or Register to comment.