Signalr отправляет запросы из концентратора в .net, но ответ никогда не запускается на стороне клиентаJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Signalr отправляет запросы из концентратора в .net, но ответ никогда не запускается на стороне клиента

Сообщение Anonymous »

Я использую клиент signalr в своем приложении для Android. Я собираюсь показать вам части моего кода, потому что это огромный проект.
У меня есть SignalRServiceConnections, который связывает службу в моей MainLayoutActivity, которая также реализует ISignalrConnectionEventListener.
Происходит следующее: концентратор отправляет данные в приложение, но метод возврата из моего концентратора .net не запускает концентратор обратного вызова в моей MainLayoutActivity.
Я также у меня есть UserProfileActiviy, который также реализует ISignalrConnectionEventListener, поскольку для этого необходимы обновления от ISignalRConnectionsEventListener, чтобы я мог обновить пользовательский интерфейс.
В моей основной активности реализуется ISignalRConnectionsEventListener:
реализует ISignalRConnectionsEventListener:

Код: Выделить всё

        package com.balu.datez;

public interface ISignalRConnectionsEventListener {

public void getUserId();
public void sendConnectSentClient(User jsonUser, String dateCreated, String sessionUserGuid, String userImages);
public void sendConnectSentCancelClient1(String userGuid, String sessionUserGuid);
public void sendConnectInviteCancelClient1(String userGuid, String sessionUserGuid);
public void sendConnectInviteClient(User jsonUser, String dateCreated, String sentUserGuid, String userImages);
public void sendConnectInviteCancelClient2(String userGuid, String sessionUserGuid);
public void SendConnectSentCancelClient2(String userGuid, String sessionUserGuid);
public void SendConnectInviteAcceptClient(User userData, String sessionUserGuid, String userGuid, String dateCreated, String userImages);
public void SendConnectSentAcceptClient(User userData, String sessionUserGuid, String userGuid, String dateCreated, String userImages);
public void SendConnectedInviteCancelClient(String userGuid, String sessionUserGuid);
public void SendConnectedSentCancelClient(String userGuid, String sessionUserGuid);
public void SendConnectedCancelClient1(String userGuid, String sessionUserGuid);
public void SendConnectedCancelClient2(String userGuid, String sessionUserGuid);
}

Intent intent2 = new Intent(this, SignalRServiceConnections.class);
bindService(intent2, connectionCon, BIND_AUTO_CREATE);

private ServiceConnection connectionFoll = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
SignalRServiceFollows.LocalBinder localBinder = (SignalRServiceFollows.LocalBinder) binder;
signalRServiceFollows = localBinder.getService();
signalRServiceFollows.addListener(MainLayoutActivity.this);
bound = true;

HubConnection hub = signalRServiceFollows.getHubConnection();
if (hub != null && hub.getConnectionState() == HubConnectionState.CONNECTED) {
interactionFragment.setSignalRServiceFollows(signalRServiceFollows);

}
}

@Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
Соединения службы SignalR:

Код: Выделить всё

public class SignalRServiceConnections extends Service {

private static final String CHANNEL_ID = "signalr_channel";
private HubConnection hubConnections;

private final IBinder binder = new LocalBinder();

public SignalRServiceConnections(){
}

private final List listeners =
new CopyOnWriteArrayList();

public void addListener(ISignalRConnectionsEventListener listener) {
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
if(hubConnections == null){
//startSignalR(); // Start hub immediately
}
}

public void removeListener(ISignalRConnectionsEventListener listener) {
listeners.remove(listener);
}

public class LocalBinder extends Binder {
public SignalRServiceConnections getService() {
return SignalRServiceConnections.this;
}
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}

@SuppressLint("ForegroundServiceType")
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
startForeground(1, createNotification());
startSignalR();  // Start hub AFTER foreground
//createNotificationChannel();
//startForeground(1, createNotification());
//startSignalR();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

return START_STICKY; // Restart if killed
}

@Override
public void onDestroy() {
stopSignalR();
super.onDestroy();
}

// ------------------- SIGNALR -------------------

private void startSignalR() {

SharedPreferences settingsLoginData = getSharedPreferences("LoginData", 0);
String userGuidSP = settingsLoginData.getString("userGuid", "");

if (hubConnections != null &&
hubConnections.getConnectionState() == HubConnectionState.CONNECTED) {
return;
}

String url = Utils.END_POINT_BASE_URL + "connectionshub";

hubConnections = HubConnectionBuilder
.create(url)
//.withTransport(TransportEnum.WEBSOCKETS)
.build();

hubConnections.setKeepAliveInterval(15_000);
hubConnections.setServerTimeout(60_000);

hubConnections.onClosed(exception -> {
//if(threadConnectConnection != null){
//    threadConnectConnection = null;
//}
//reconnect();// retry every 3s
});

hubConnections.on("GetUserGuid", () -> {
if(hubConnections != null && hubConnections.getConnectionState() == HubConnectionState.CONNECTED){
hubConnections.send("SendClientSessionGuid", userGuidSP);
}

for (ISignalRConnectionsEventListener l : listeners) {
l.getUserId();
}
//l.onConnectInvite(user, dateCreated, userImages);

//activity.runOnUiThread(() -> Toast.makeText(activity, "SendClientSessionGuid", Toast.LENGTH_SHORT).show());
});

hubConnections.on("SendConnectSentClient", (user, dateCreated, sessionUserGuid, userImage) -> {
// This lambda is called when the hub sends a message

if(sessionUserGuid.equals(userGuidSP)){

try{
Gson gson = new Gson();
User userObj = gson.fromJson(user, User.class);

//interactionsFragment.sendConnectsSentNotifications(user, dateCreated, userImages);

for (ISignalRConnectionsEventListener l : listeners) {
l.sendConnectSentClient(userObj, dateCreated, sessionUserGuid, userImage);
}
} catch (Exception e) {
throw new RuntimeException(e);
}

// Update UI (must be on main thread)
//activity.runOnUiThread(() -> {

//});
}
}, String.class, String.class, String.class, String.class);

hubConnections.on("SendConnectSentCancelClient1", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)) {
//interactionsFragment.sendConnectSentDeletedNotifications(userGuid);

for (ISignalRConnectionsEventListener l : listeners) {
l.sendConnectSentCancelClient1(userGuid, sessionUserGuid);
}
}

}, String.class, String.class);

hubConnections.on("SendConnectInviteCancelClient1", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
//interactionsFragment.sendConnectInviteDeletedNotifications(userGuid);
for (ISignalRConnectionsEventListener l : listeners) {
l.sendConnectInviteCancelClient1(userGuid, sessionUserGuid);
}

}

}, String.class, String.class);

hubConnections.on("SendConnectInviteClient", (jsonUser, dateCreated, sentUserGuid, userImages) ->  {
// This lambda is called when the hub sends a message

if(sentUserGuid.equals(userGuidSP)) {
try{
Gson gson = new Gson();
User user = gson.fromJson(jsonUser, User.class);

//interactionsFragment.sendConnectsInviteNotifications(user, dateCreated, userImages);

for (ISignalRConnectionsEventListener l : listeners) {
l.sendConnectInviteClient(user, dateCreated, sentUserGuid, userImages);
}

} catch (Exception e) {
throw new RuntimeException(e);
}
}

// Update UI (must be on main thread)
//activity.runOnUiThread(() -> {

//});
}, String.class, String.class, String.class, String.class);

hubConnections.on("SendConnectInviteCancelClient2", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
for (ISignalRConnectionsEventListener l : listeners) {
l.sendConnectInviteCancelClient2(userGuid, sessionUserGuid);
}
}

}, String.class, String.class);

hubConnections.on("SendConnectSentCancelClient2", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectSentCancelClient2(userGuid, sessionUserGuid);
}
//interactionsFragment.sendConnectSentDeletedNotifications(userGuid);
}

}, String.class, String.class);

hubConnections.on("SendConnectInviteAcceptClient", (userData, sessionUserGuid, userGuid, dateCreated, userImages) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)
if(sessionUserGuid.equals(userGuidSP)) {
try{
Gson gson = new Gson();
User user = gson.fromJson(userData, User.class);

for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectInviteAcceptClient(user, sessionUserGuid, userGuid, dateCreated, userImages);
}

//interactionsFragment.sendConnectInviteDeletedNotifications(userGuid);
//interactionsFragment.sendConnectsConnectionsAddedNotifications(user, dateCreated, userImages);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}, String.class, String.class, String.class, String.class, String.class);

hubConnections.on("SendConnectSentAcceptClient", (userData, sessionUserGuid, userGuid, dateCreated, userImages) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)
if(sessionUserGuid.equals(userGuidSP)) {
try{
Gson gson = new Gson();
User user = gson.fromJson(userData, User.class);

for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectSentAcceptClient(user, sessionUserGuid, userGuid, dateCreated, userImages);
}
//interactionsFragment.sendConnectSentDeletedNotifications(userGuid);
//interactionsFragment.sendConnectsConnectionsAddedNotifications(user, dateCreated, userImages);
} catch (Exception e) {
throw new RuntimeException(e);
}
}

}, String.class, String.class, String.class, String.class, String.class);

hubConnections.on("SendConnectedInviteCancelClient", (sessionUserGuid, userGuid) ->  {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
//interactionsFragment.sendConnectsConnectionsDeletedNotifications(userGuid);
//interactionsFragment.sendConnectInviteDeletedNotifications(userGuid);
for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectedInviteCancelClient(userGuid, sessionUserGuid);
}
}

}, String.class, String.class);

hubConnections.on("SendConnectedSentCancelClient", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
//interactionsFragment.sendConnectsConnectionsDeletedNotifications(userGuid);
//interactionsFragment.sendConnectSentDeletedNotifications(userGuid);
for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectedSentCancelClient(userGuid, sessionUserGuid);
}
}

}, String.class, String.class);

hubConnections.on("SendConnectedCancelClient1", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectedCancelClient1(userGuid, sessionUserGuid);
}
//interactionsFragment.sendConnectsConnectionsDeletedNotifications(userGuid);
}

}, String.class, String.class);

hubConnections.on("SendConnectedCancelClient2", (sessionUserGuid, userGuid) -> {
// This lambda is called when the hub sends a message

// Update UI (must be on main thread)

if(sessionUserGuid.equals(userGuidSP)){
for (ISignalRConnectionsEventListener l : listeners) {
l.SendConnectedCancelClient2(userGuid, sessionUserGuid);
}
//interactionsFragment.sendConnectsConnectionsDeletedNotifications(userGuid);
}

}, String.class, String.class);

//signalConnectionsMainHelper = new SignalRConnectionsMainHelper(this.activity, this.interactionsFragment, userGuidSP, hubConnection);
//hubConnection.onClosed(Exception -> {
// // Дополнительно журнал
// });
//
// // Пример метода концентратора
//hubConnection.on("ReceiveMessage", (user, message) -> {
// // Транслируем событие в Activity / UI
// }, String.class, String.class);

Код: Выделить всё

    Executors.newSingleThreadExecutor().execute(() ->  {
try {
hubConnections.start().blockingAwait();
} catch (Exception e) {
e.printStackTrace();
}
});
}

private void stopSignalR() {
if (hubConnections != null) {
hubConnections.stop();
hubConnections = null;
}
}

public HubConnection getHubConnection() {
return hubConnections;
}

// ------------------- NOTIFICATION -------------------

private Notification createNotification() {
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("SignalR Connected")
.setContentText("Running in background")
.setSmallIcon(android.R.drawable.stat_notify_sync)
.setOngoing(true)
.build();
}

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"SignalR Service",
NotificationManager.IMPORTANCE_LOW
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}
И это концентратор отправляет данные для хранения данных в базе данных, а затем должен вызвать sendConnectSentClient, но происходит сбой.
Я тестировал это, и у меня есть некоторые успехи, когда ответ пришел от концентратора, но большую часть времени концентратор не запускает обратный вызов.
Концентратор был протестирован при создании концентратора иначе, чем при использовании службы для концентратора и хаб отреагировал хорошо, но когда я выхожу из приложения и возвращаюсь в приложение, хаб снова подключается, а мне этого не хотелось. я хочу, чтобы концентратор работал и работал до тех пор, пока концентратор может оставаться в рабочем состоянии.
ПРИМЕЧАНИЕ. GetUserGuid вызывается из концентратора клиенту, но когда я отправляю данные в концентратор, обратные вызовы концентратора клиента никогда не срабатывают.

Подробнее здесь: https://stackoverflow.com/questions/798 ... lient-side
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»