Signalr sendet Anfragen vom Hub in .net, aber die Antwort löst nie die Clientseite ausC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Signalr sendet Anfragen vom Hub in .net, aber die Antwort löst nie die Clientseite aus

Post by Anonymous »

Ich verwende einen Signalr-Client in meiner Android-App. Ich werde Ihnen Teile meines Codes zeigen, weil es ein riesiges Projekt ist.
Ich habe eine SignalRServiceConnections, die den Dienst in meiner MainLayoutActivity bindet, die auch ISignalrConnectionEventListener implementiert.
Was passiert, ist, dass der Hub die Daten an die Anwendung sendet, aber die Rückgabemethode von meinem .net-Hub den Callback-Hub in meiner MainLayoutActivity nicht auslöst.
Ich habe auch eine UserProfileActiviy, das auch ISignalrConnectionEventListener implementiert, da hierfür Aktualisierungen von ISignalRConnectionsEventListener erforderlich sind, damit ich die Benutzeroberfläche aktualisieren kann.
In meiner Hauptlayout-Aktivität wird ISignalRConnectionsEventListener implementiert:
Implementiert ISignalRConnectionsEventListener:

Code: Select all

        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 connectionCon = new ServiceConnection()        {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
SignalRServiceConnections.LocalBinder localBinder = (SignalRServiceConnections.LocalBinder) binder;
signalRServiceConnections = localBinder.getService();
bound = true;
signalRServiceConnections.addListener(MainLayoutActivity.this);

HubConnection hub = signalRServiceConnections.getHubConnection();
if (hub != null && hub.getConnectionState() == HubConnectionState.CONNECTED) {
interactionFragment.setSignalRServiceConnections(signalRServiceConnections);
}
}

@Override
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};

@Override
protected void onStart() {
super.onStart();

//bindService(new Intent(this, SignalRServiceFollows.class), connectionFoll, BIND_AUTO_CREATE);

}

@Override
protected void onStop() {
super.onStop();
if (bound) {
if(connectionCon != null){
unbindService(connectionCon);
}
if(connectionFoll != null){
//unbindService(connectionFoll);
}
bound = false;
}
}
Die SignalR ServiceConnections:

Code: Select all

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 -> {
//            // Optionally log
//        });
//
//        // Example hub method
//        hubConnection.on("ReceiveMessage", (user, message) -> {
//            // Broadcast event to Activities / 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);
}
}
Und das ist, dass der Hub die Daten sendet, um die Daten in der Datenbank zu speichern, dann sollte er sendConnectSentClient aufrufen, schlägt aber fehl.
Ich habe dies getestet und einige Erfolge erzielt, wenn die Antwort vom Hub zurückgekommen ist, aber die meiste Zeit löst der Hub seinen Rückruf nicht aus.
Der Hub wurde beim Erstellen des Hubs anders getestet als bei der Verwendung eines Dienstes für den Hub und den Der Hub hat gut reagiert, aber wenn ich die App verlasse und zurück in die App gehe, stellt der Hub die Verbindung wieder her und ich wollte das nicht. Ich möchte, dass der Hub läuft und am Leben bleibt, solange der Hub am Leben bleiben kann.
HINWEIS: Die GetUserGuid wird vom Hub zum Client aufgerufen, aber wenn ich Daten an den Hub sende, werden die Rückrufe des Client-Hubs nie ausgelöst.
Der Signalr-Hub:

Code: Select all

using DatezApi.Models;
using DatezApi.Repository.Interface;
using DatezApi.Repository.Service;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json.Linq;
using System.Text.Json;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace DatezApi.Hub
{
public class ConnectionsHub : Hub
{

private readonly IConnectRepository connectRepository;
private readonly IUserRepository userRepository;
private readonly IProfileRespository profileRepository;
private readonly IConnectedRepository connectedRepository;

public ConnectionsHub(IConnectRepository connectRepository, IUserRepository userRepository, IProfileRespository profileRepository, IConnectedRepository connectedRepository)
{
this.connectRepository = connectRepository;
this.userRepository = userRepository;
this.profileRepository = profileRepository;
this.connectedRepository = connectedRepository;
}
public override async Task OnConnectedAsync()
{
Clients.Client(Context.ConnectionId).GetUserGuid();
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
UserConnectConnections.Disconnect(Context.ConnectionId);
}
public async Task SendClientSessionGuid(string guid)
{
UserConnectConnections.Connect(Context.ConnectionId, guid);
}

public async Task SendConnectSent(string sessionUserGuid, string userGuid)
{
TblConnect connect = await connectRepository.StoreConnect(userGuid, sessionUserGuid);

TblUser userSent = await userRepository.GetUserByGuid(userGuid);
TblUser userInvite = await userRepository.GetUserByGuid(sessionUserGuid);

string userSentJson = System.Text.Json.JsonSerializer.Serialize(userSent);
string userInviteJson = System.Text.Json.JsonSerializer.Serialize(userInvite);

TblPersonalDetail sentPersonalDetail = await profileRepository.GetProfileByUserGuid(userGuid);
TblPersonalDetail invitePersonalDetail = await profileRepository.GetProfileByUserGuid(sessionUserGuid);

string sentUserConnectionId = UserConnectConnections.connections.FirstOrDefault(x => x.Value.Equals(userGuid)).Key;

await Clients.Client(Context.ConnectionId).SendConnectSentClient(userSentJson, connect.DateCreated.ToString("o"), sessionUserGuid, sentPersonalDetail.Images);
if (sentUserConnectionId != null)
{
await Clients.Client(sentUserConnectionId).SendConnectInviteClient(userInviteJson, connect.DateCreated.ToString("o"), userGuid, invitePersonalDetail.Images);
}

}
public async Task SendConnectSentCancel(string sessionUserGuid, string userGuid)
{
await connectRepository.DeleteConnect(sessionUserGuid, userGuid);
string sentUserConnectionId = UserConnectConnections.connections.FirstOrDefault(x => x.Value.Equals(userGuid)).Key;
await Clients.Client(Context.ConnectionId).SendConnectSentCancelClient1(sessionUserGuid, userGuid);

if (sentUserConnectionId != null)
{
await Clients.Client(sentUserConnectionId).SendConnectInviteCancelClient1(userGuid, sessionUserGuid);
}
}
public async Task SendConnectInviteCancel(string sessionUserGuid, string userGuid)
{
await connectRepository.DeleteConnect(sessionUserGuid, userGuid);
string inviteUserConnectionId = UserConnectConnections.connections.FirstOrDefault(x => x.Value.Equals(userGuid)).Key;
await Clients.Client(Context.ConnectionId).SendConnectInviteCancelClient2(sessionUserGuid, userGuid);

if (inviteUserConnectionId != null)
{
await Clients.Client(inviteUserConnectionId).SendConnectSentCancelClient2(userGuid, sessionUserGuid);
}
}
public async Task SendConnectAccept(bool isInvite, string sessionUserGuid, string userGuid)
{
await connectRepository.DeleteConnect(sessionUserGuid, userGuid);

TblConnected connected = await connectedRepository.StoreConnected(userGuid, sessionUserGuid);

string userConnectionId = UserConnectConnections.connections.FirstOrDefault(x =>  x.Value.Equals(userGuid)).Key;

TblUser userSent = await userRepository.GetUserByGuid(userGuid);
TblUser userInvite = await userRepository.GetUserByGuid(sessionUserGuid);

string userSentJson = System.Text.Json.JsonSerializer.Serialize(userSent);
string userInviteJson = System.Text.Json.JsonSerializer.Serialize(userInvite);

TblPersonalDetail sentPersonalDetail = await profileRepository.GetProfileByUserGuid(userGuid);
TblPersonalDetail invitePersonalDetail = await profileRepository.GetProfileByUserGuid(sessionUserGuid);

if (isInvite)
{
await Clients.Client(Context.ConnectionId).SendConnectInviteAcceptClient(userSentJson, sessionUserGuid, userGuid, connected.DateCreated.ToString("o"), sentPersonalDetail.Images);

if (userConnectionId != null)
{
await Clients.Client(userConnectionId).SendConnectSentAcceptClient(userInviteJson, userGuid, sessionUserGuid, connected.DateCreated.ToString("o"), invitePersonalDetail.Images);
}
}
else
{
await Clients.Client(Context.ConnectionId).SendConnectSentAcceptClient(userInviteJson, sessionUserGuid, userGuid, connected.DateCreated.ToString("o"), invitePersonalDetail.Images);

if (userConnectionId != null)
{
await Clients.Client(userConnectionId).SendConnectInviteAcceptClient(userSentJson, userGuid, sessionUserGuid, connected.DateCreated.ToString("o"), sentPersonalDetail.Images);
}
}
}

public async Task SendConnectedCancel(string sessionUserGuid, string userGuid)
{
await connectedRepository.DeleteConnected(userGuid, sessionUserGuid);

string userConnectionId = UserConnectConnections.connections.FirstOrDefault(x => x.Value.Equals(userGuid)).Key;

await Clients.Client(Context.ConnectionId).SendConnectedInviteCancelClient(sessionUserGuid, userGuid);

if (userConnectionId != null)
{
await Clients.Client(userConnectionId).SendConnectedSentCancelClient(userGuid, sessionUserGuid);
}

}
public async Task SendConnectedCancel2(string sessionUserGuid, string userGuid)
{
await connectedRepository.DeleteConnected(userGuid, sessionUserGuid);

string userConnectionId = UserConnectConnections.connections.FirstOrDefault(x => x.Value.Equals(userGuid)).Key;

await Clients.Client(Context.ConnectionId).SendConnectedCancelClient1(sessionUserGuid, userGuid);

if (userConnectionId != null)
{
await Clients.Client(userConnectionId).SendConnectedCancelClient2(userGuid, sessionUserGuid);
}

}

}
public interface IComHub
{
Task GetUserGuid();
Task SendConnectSentClient(string user, string dateCreated, string sessionUserGuid, string userImage);
Task SendConnectInviteClient(string user, string dateCreated, string sentUserGuid, string userImage);
Task SendConnectSentCancelClient1(string sessionUserGuid, string userGuid);
Task SendConnectInviteCancelClient1(string sessionUserGuid, string userGuid);
Task SendConnectSentCancelClient2(string sessionUserGuid, string userGuid);
Task SendConnectInviteCancelClient2(string sessionUserGuid, string userGuid);
Task SendConnectInviteAcceptClient(string user, string sessionUserGuid, string userGuid, string dateCreated, string images);
Task SendConnectSentAcceptClient(string user, string sessionUserGuid, string userGuid, string dateCreated, string images);
Task SendConnectedInviteCancelClient(string sessionUserGuid, string userGuid);
Task SendConnectedSentCancelClient(string sessionUserGuid, string userGuid);
Task SendConnectedCancelClient1(string sessionUserGuid, string userGuid);
Task SendConnectedCancelClient2(string sessionUserGuid, string userGuid);

}
}
wenn ich anrufe:

Code: Select all

                                signalRConnectionsProfileHelper.getHubConnection().send("SendConnectSent", userSessionGuid, userProfileGuid);
Diese Daten werden in der Datenbank gespeichert, aber es gibt eine Antwort, die an den Hub zurückkommt, den ich in der SignalRServiceConnections-Datei gefunden habe:

Code: Select all

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);
Wird aber nie angerufen

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post