Xamarin socket.io connect on button press

2019-07-24 17:50发布

I started using xamarin yesterday so I am quite new to both C# and how it works yet. Have been using Socket.io for a while in other projects tho. What I am trying to do right now is connect to the server the user inputs in a TextEdit. Take that URL and connect on click, and it works fine it connects. The problem is that it just keeps on connecting and creating more and more sockets all connected to the server at the same time. If I add manualresetevent.waitOne(5000); it will only create one socket. But this is kind of inconvenient. This will just continue to create sockets and not stop. PS: Only happens on button click not if I put the connection in the OnCreate.

public class MainActivity : Activity
{
    private ManualResetEvent ManualResetEvent = null;
    private Socket socket = null;
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        var count = 0;

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        ManualResetEvent = new ManualResetEvent(false);
        Button testConnection = FindViewById<Button>(Resource.Id.test);
        EditText serverURL = FindViewById<EditText>(Resource.Id.serverURL);
        TextView view = FindViewById<TextView>(Resource.Id.debug);
        testConnection.Click += delegate
        {
            count++;
            socket = IO.Socket(serverURL.Text);
            view.Text = count.ToString();
            socket.On("connect", () =>
            {

            });
            socket.On(Socket.EVENT_CONNECT_ERROR, () =>
            {

            });  
        };
    }
}

And My other version which only creates two sockets. The difference being the socket.Connect()

public class MainActivity : Activity
{
    private ManualResetEvent ManualResetEvent = null;
    private Socket socket = null;
    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        var count = 0;

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);
        ManualResetEvent = new ManualResetEvent(false);
        Button testConnection = FindViewById<Button>(Resource.Id.test);
        EditText serverURL = FindViewById<EditText>(Resource.Id.serverURL);
        TextView view = FindViewById<TextView>(Resource.Id.debug);
        testConnection.Click += delegate
        {
            count++;
            socket = IO.Socket(serverURL.Text);
            socket.Connect();
            view.Text = count.ToString();
            socket.On("connect", () =>
            {

            });
            socket.On(Socket.EVENT_CONNECT_ERROR, () =>
            {

            });  
        };
    }
}

I am using this component https://components.xamarin.com/view/socketioclientdotnet

0条回答
登录 后发表回答