我正在使用 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 作業室:
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;
});
}
}
uj5u.com熱心網友回復:
經過大量研究,我設法解決了這個問題。我正在寫這個問題的解決方案。我希望它能解決別人的問題
處理信號器連接關閉:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/462593.html
