SignalR 与 React Native Expo:: 没有发生任何事情

发布于 2025-01-20 10:47:57 字数 2999 浏览 0 评论 0 原文

我有一个具有消息功能的移动应用程序。后端是.NET Core 6.0控制台应用程序。前端是React Native Expo应用程序。当用户键入“发送”按钮时,它将消息保存在数据库中,并将新消息推向另一个用户的屏幕(目前仅是一对一的对话)。一切都起作用,除非它试图将新消息推向收件人。我已经在Stackoverflow上尝试过其他解决方案,但是到目前为止,没有一个没有帮助...

.NET应用程序托管在Azure上,我正在使用实际设备运行Expo应用程序。

新消息没有被推到收件人的屏幕上。我之前遇到了404个错误,但事实证明是其他错误。我浏览了代码,然后执行了 _MessageHub.clients.all.sendasync(“接收到”,消息); fine,但其他手机没有收到新消息。

REACT本地博览会代码:

import { HubConnectionBuilder } from '@microsoft/signalr';
import React, { useEffect, useState } from 'react';

export default function Conversation({ navigation, route }: any) {
    const [messages, setMessages] = useState([]);
    const [message, setMessage] = useState("");
    const conversation = route.params.data;
    const personId = getCurrentUser().personId;

    useEffect(() => {
        loadMessages();

        try {
            const connection = new HubConnectionBuilder()
                .withUrl(`${Settings.ApiUrl}/hubs-message`)
                .build();
            connection.start().then(() => console.log("started"));
            connection.on("ReceivedMessage", message => {
                console.log(message);
                let updateMessage = messages;
                updateMessage.unshift(message);
                setMessages(updateMessage);
            });
        }
        catch (e) { console.error("error here", e); }
    }, []);

    const sendMessage = () => {
        postUser(`${Settings.ApiUrl}/v1/Message/Send`, {
            message: message,
            conversationId: conversation.id
        }).then((data: any) => {
            setMessage("");
            let updateMessages = [...messages];
            updateMessages.unshift(data.Message);
            setMessages(updateMessages);
        });
    };
....
....
}

.net核心代码:

program.cs

builder.Services.AddSignalR();
var app = builder.Build();
...
...
app.UseCors();
app.UseHttpsRedirection();
app.MapControllers();
app.UseAuthentication();
app.UseAuthorization();
app.MapHub<MessageHub>("/hubs-message");

messageHub.cs //没有太多目前...

[Authorize]
public class MessageHub : Hub
{
    
}

notificationationservice.cs // MessageController将消息保存到数据库以将新消息推向收件人之后。

public class NotificationService
{
    private readonly IHubContext<MessageHub> _messageHub;
    public NotificationService(IHubContext<MessageHub> messageHub) 
    { 
        _messageHub = messageHub;
    }
    ...
    ...
    if (newMessageSentData.ActiveOnConversationId == conversationId)
    {
        try
        {
           //push new message to receiver
           _messageHub.Clients.All.SendAsync("ReceivedMessage", message);
        }
        catch (Exception ex)
        {
           //NO exception thrown
           var a = ex.Message;
        }
    }
}

I have a mobile app with messaging functionality. The backend is a .NET Core 6.0 console application. The front end is a React Native Expo application. When a user hits the "send" button, it saves the message in the database and pushes the new message to the other user's screen (currently it's only one to one conversation). Everything works except when it's trying to push the new message to the recipient. I have tried other solutions on Stackoverflow but none so far has been helpful...

The .NET application is hosted on Azure and I am using the actual device to run the Expo app.

The new message is not pushed to the recipient's screen. I was getting some 404 errors before but turned out to be something else. I walked through the code and it executed the _messageHub.Clients.All.SendAsync("ReceivedMessage", message); fine but the other phone is not getting the new message.

React Native Expo code:

import { HubConnectionBuilder } from '@microsoft/signalr';
import React, { useEffect, useState } from 'react';

export default function Conversation({ navigation, route }: any) {
    const [messages, setMessages] = useState([]);
    const [message, setMessage] = useState("");
    const conversation = route.params.data;
    const personId = getCurrentUser().personId;

    useEffect(() => {
        loadMessages();

        try {
            const connection = new HubConnectionBuilder()
                .withUrl(`${Settings.ApiUrl}/hubs-message`)
                .build();
            connection.start().then(() => console.log("started"));
            connection.on("ReceivedMessage", message => {
                console.log(message);
                let updateMessage = messages;
                updateMessage.unshift(message);
                setMessages(updateMessage);
            });
        }
        catch (e) { console.error("error here", e); }
    }, []);

    const sendMessage = () => {
        postUser(`${Settings.ApiUrl}/v1/Message/Send`, {
            message: message,
            conversationId: conversation.id
        }).then((data: any) => {
            setMessage("");
            let updateMessages = [...messages];
            updateMessages.unshift(data.Message);
            setMessages(updateMessages);
        });
    };
....
....
}

.NET Core code:

Program.cs

builder.Services.AddSignalR();
var app = builder.Build();
...
...
app.UseCors();
app.UseHttpsRedirection();
app.MapControllers();
app.UseAuthentication();
app.UseAuthorization();
app.MapHub<MessageHub>("/hubs-message");

MessageHub.cs //does not have much at the moment...

[Authorize]
public class MessageHub : Hub
{
    
}

NotificationService.cs //this is called by the MessageController after saving the message to the database to push the new message to the recipient.

public class NotificationService
{
    private readonly IHubContext<MessageHub> _messageHub;
    public NotificationService(IHubContext<MessageHub> messageHub) 
    { 
        _messageHub = messageHub;
    }
    ...
    ...
    if (newMessageSentData.ActiveOnConversationId == conversationId)
    {
        try
        {
           //push new message to receiver
           _messageHub.Clients.All.SendAsync("ReceivedMessage", message);
        }
        catch (Exception ex)
        {
           //NO exception thrown
           var a = ex.Message;
        }
    }
}

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

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

发布评论

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

评论(1

乖乖兔^ω^ 2025-01-27 10:47:57

我能够通过转移到Azure Signalr来使它起作用。设置非常容易。这是一个YouTube视频,显示要执行此操作 https://wwww.youtube。 com/watch?v = wpqzrq6wnbw&amp; t = 759s

Azure Portal

将SignalR服务添加到我的资源组中,并在设置下复制连接字符串 group

program.cs

builder.Services.AddSignalR().AddAzureSignalR("[Azure SignalR Connection String]");
var app = builder.Build();
...
...
app.UseAzureSignalR(routes =>
{
    routes.MapHub<MessageHub>("/hubs-message");
});

I was able to get it to work by moving to Azure SignalR. It's quite easy to set up. Here is a youtube video showing to to do that https://www.youtube.com/watch?v=wpQZrQ6Wnbw&t=759s.

Azure portal

Add the SignalR service to my resource group and copy the connection string under the Settings group

program.cs,

builder.Services.AddSignalR().AddAzureSignalR("[Azure SignalR Connection String]");
var app = builder.Build();
...
...
app.UseAzureSignalR(routes =>
{
    routes.MapHub<MessageHub>("/hubs-message");
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文