我使用SignalR创建了一个聊天应用程序。但是,当我发送消息时,所有客户端都会收到。但我想启用两个特定个人之间的消息传递。我想测试两个模拟器之间的消息传递。有人能帮我做这件事吗?
using Microsoft.Maui.Devices;
using Microsoft.Maui.Media;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Maui.Media;
using Microsoft.Maui.ApplicationModel;
using Microsoft.AspNetCore.SignalR.Client;
namespace SignalRClient
{
public partial class MainPage : ContentPage
{
private readonly HubConnection hubConnection;
private IEnumerable<Locale> locales;
private CancellationTokenSource cancellationTokenSource;
public MainPage()
{
InitializeComponent();
string baseUrl = DeviceInfo.Current.Platform == DevicePlatform.Android ? "http://10.0.2.2" : "http://localhost";
hubConnection = new HubConnectionBuilder()
.WithUrl($"{baseUrl}:5127/chatHub")
.Build();
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{
this.Dispatcher.DispatchAsync(() =>
{
lblChat.Text += $"<b>{user}</b>: {message}<br/>";
});
});
_ = ConnectToHubAsync();
cancellationTokenSource = new CancellationTokenSource();
}
protected override async void OnAppearing()
{
base.OnAppearing();
locales = await TextToSpeech.GetLocalesAsync();
foreach (var locale in locales)
{
Languages.Items.Add(locale.Language);
}
Languages.SelectedIndex = 10;
Languages.IsVisible = true;
await FirstStartListening(); // Yeni eklenen çaÄrı
}
private async Task ConnectToHubAsync()
{
try
{
await hubConnection.StartAsync();
}
catch (Exception ex)
{
Console.WriteLine($"Error connecting to Hub: {ex.Message}");
}
}
private async Task StartListening()
{
var isGranted = await Permissions.CheckStatusAsync<Permissions.Microphone>();
if (isGranted != PermissionStatus.Granted)
{
isGranted = await Permissions.RequestAsync<Permissions.Microphone>();
}
if (isGranted == PermissionStatus.Granted)
{
var cultureInfo = new CultureInfo("tr-TR");
cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
try
{
UpdateUI("Ses tanıma baÅlatılıyor...");
var recognitionResult = await SpeechToText.Default.ListenAsync(
cultureInfo,
new Progress<string>(partialText => UpdateUI(partialText)),
cancellationToken);
if (recognitionResult != null && recognitionResult.IsSuccessful)
{
var usertext = recognitionResult.Text.ToLowerInvariant();
this.Dispatcher.DispatchAsync(() =>
{
txtMessage.Text = usertext; // Tanınan metni "Enter your message" alanına yazdır
});
if (usertext.Contains("sesli mesaj gönder"))
{
btnRecord_Clicked(this, EventArgs.Empty);
}
else if (usertext.Contains("mesaj gönder"))
{
btnSend_Clicked(this, EventArgs.Empty);
}
}
else
{
UpdateUI("Tekrar dene.");
}
}
catch (OperationCanceledException)
{
UpdateUI("Ses tanıma iptal edildi.");
}
catch (Exception ex)
{
UpdateUI($"Hata: {ex.Message}");
}
}
else
{
UpdateUI("Mikrofon izni verilmedi.");
}
}
private void UpdateUI(string message)
{
this.Dispatcher.DispatchAsync(() =>
{
txtMessage.Text = message;
});
}
private async void btnSend_Clicked(object sender, EventArgs e)
{
await SendAndSpeakAsync();
}
private async Task SendAndSpeakAsync()
{
try
{
await hubConnection.InvokeAsync("SendMessageToAll", txtUsername.Text, txtMessage.Text);
if (Languages.SelectedIndex >= 0)
{
var selectedLocale = locales.ElementAt(Languages.SelectedIndex);
await TextToSpeech.SpeakAsync(txtMessage.Text, new SpeechOptions { Locale = selectedLocale });
}
txtMessage.Text = string.Empty;
}
catch (Exception ex)
{
Console.WriteLine($"Error sending message: {ex.Message}");
}
}
private async Task FirstStartListening()
{
var isGranted = await CheckAndRequestMicrophonePermission();
if (!isGranted)
{
UpdateUI("Mikrofon izni verilmedi.");
return;
}
var cultureInfo = new CultureInfo("tr-TR");
while (true)
{
if (cancellationTokenSource.Token.IsCancellationRequested)
{
break;
}
var recognitionResult = await SpeechToText.Default.ListenAsync(
cultureInfo,
new Progress<string>(partialText => { }),
cancellationTokenSource.Token);
if (recognitionResult.IsSuccessful)
{
var usertext = recognitionResult.Text.ToLowerInvariant();
this.Dispatcher.DispatchAsync(() =>
{
txtMessage.Text = usertext; // Tanınan metni "Enter your message" alanına yazdır
});
if (usertext.Contains("sesli mesaj gönder"))
{
btnRecord_Clicked(this, EventArgs.Empty);
}
else if (usertext.Contains("mesaj gönder"))
{
btnSend_Clicked(this, EventArgs.Empty);
}
}
}
}
private static async Task<bool> CheckAndRequestMicrophonePermission()
{
var status = await Permissions.CheckStatusAsync<Permissions.Microphone>();
if (status != PermissionStatus.Granted)
{
status = await Permissions.RequestAsync<Permissions.Microphone>();
}
return status == PermissionStatus.Granted;
}
// Ses kaydı butonu için tıklama olayı
private async void btnRecord_Clicked(object sender, EventArgs e)
{
cancellationTokenSource?.Cancel();
cancellationTokenSource = new CancellationTokenSource();
await StartListening();
}
}
}
using Microsoft.AspNetCore.SignalR;
namespace SignalRServer.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessageToAll(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
using SignalRServer.Hubs;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapHub<ChatHub>("/chatHub");
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=ChatDemo}/{id?}");
app.Run();
我尝试了几种方法,但始终无法完成。我尝试使用连接ID,但遇到错误。