java Android中的Signalr连接事件手柄

发布于 2025-01-21 14:55:18 字数 3113 浏览 0 评论 0原文

我正在使用SignalR来制作两人在线游戏。到目前为止,一切都很好。但是,当一个玩家的互联网被切断(以几毫秒为单位)或由于任何原因切断服务器时,该程序将不再起作用。如何通知连接事件? 如何自动重新连接?

我已经研究了很长时间,但是我还没有找到解决方案

ASP.NET Core 5.0服务器端:

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

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

客户端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;

        });
    }


}

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;

        });
    }


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

星星的軌跡 2025-01-28 14:55:18

经过大量研究,我设法解决了这个问题。我正在写解决这个问题的解决方案。我希望它能解决别人的问题

处理信号连接关闭:

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

处理信号连接开始:

    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 

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 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文