Home > Software design >  signalr connection event handle in java android
signalr connection event handle in java android

Time:04-19

I'm using SignalR to make a two-player online game. So far so good. But when one of the players' internet is cut off ( in a few milliseconds) or the server is cut off for any reason, the program no longer works. How can I be notified of connection events? How can I reconnect automatically?

I have been researching it for a long time, but I have not found a solution

Asp.NET core 5.0 server-side:

    public class ChatHub : Hub
    {
        LogHelper logHelper = new LogHelper("hub");

        public async Task Move(float x, float y)
        {
                await Clients.Others.SendAsync("ReceivePosition", x, y);
        }
}

client-side java android studio :

public class MainActivity extends AppCompatActivity {


    private static final String TAG = "qazwsx";
    Button btnStart;
    View viewMove;

    HubConnection hubConnection;

    @SuppressLint({"ClickableViewAccessibility", "CheckResult"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hubConnection = HubConnectionBuilder.create("http://192.168.1.10:45455/notification").build();

        hubConnection.on("ReceivePosition", (x, y) -> {

            runOnUiThread(() -> {
                viewMove.setX(x);
                viewMove.setY(y);

                Log.i(TAG, String.format("onCreate: x:%s  y:%s", x, y));
            });

        }, Float.class, Float.class);

        btnStart = findViewById(R.id.bntStart);
        viewMove = findViewById(R.id.viewMove);


        btnStart.setOnClickListener(view -> {
            Log.i(TAG, "onCreate > btnStart.setOnClickListener > status:"   hubConnection.getConnectionState());
            if (btnStart.getText().toString().equals("START")) {
                if (hubConnection.getConnectionState() == HubConnectionState.DISCONNECTED) {
                    btnStart.setText("STOP");
                }
            } else {
                if (hubConnection.getConnectionState() == HubConnectionState.CONNECTED) {
                    hubConnection.stop();

                }
            }
        });

        final float[] dX = new float[1];
        final float[] dY = new float[1];
        viewMove.setOnTouchListener((view, event) -> {

            switch (event.getAction()) {
                //this is your code
                case MotionEvent.ACTION_DOWN:
                    dX[0] = view.getX() - event.getRawX();
                    dY[0] = view.getY() - event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    view.animate()
                            .x(event.getRawX()   dX[0])
                            .y(event.getRawY()   dY[0])
                            .setDuration(0)
                            .start();
                    if (hubConnection.getConnectionState() == HubConnectionState.CONNECTED) {
                        hubConnection.send("Move", event.getRawX()   dX[0], event.getRawY()   dY[0]);
                        Log.i(TAG, String.format("move: x:%s  y:%s", dX[0], dY[0]));

                    }
                    break;
                default:
                    return false;
            }
            return true;

        });
    }


}

CodePudding user response:

After much research, I managed to solve this problem. I am writing the solution to this problem. I hope it solves someone else's problem

handle the signalr connection close:

hubConnection.onClosed(exception -> {
            //do something
            //attemt to connect
            //note: exception is null when the user stop connection
        });

handle the signalr connection start:

    hubConnection.start()
                            .doOnError(throwable -> {
                                Log.e(TAG, "doInBackground > doOnError: ", throwable);
//start fail , try again    
//note: the start function need try chach when we use this function
                            })
                            .doOnComplete(() -> {
                                Log.i(TAG, "doInBackground > doOnComplete.");
                                //start complated
                            })
                            .blockingAwait();//you must write this function ,else other function not worck 
  • Related