-
Notifications
You must be signed in to change notification settings - Fork 381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
InvokeAsync(StateHasChanged) from StateHasChanged() #239
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,7 @@ | ||
using System; | ||
using System.Collections.Concurrent; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
|
||
using Microsoft.AspNetCore.SignalR; | ||
|
@@ -8,22 +11,42 @@ namespace BlazorChat | |
public class BlazorChatSampleHub : Hub | ||
{ | ||
public const string HubUrl = "/chat"; | ||
private static ConcurrentDictionary<string, string> _connectedUsers = new ConcurrentDictionary<string, string>(); | ||
|
||
public async Task Broadcast(string username, string message) | ||
{ | ||
await Clients.All.SendAsync("Broadcast", username, message); | ||
} | ||
public async Task SendUserToUser(string senderUsername, string recipientUsername, string message) | ||
{ | ||
var recipientConnectionId = _connectedUsers.FirstOrDefault(u => u.Value == recipientUsername).Key; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Cache by userId as key so you don't need to find by value. |
||
if (!string.IsNullOrEmpty(recipientConnectionId)) | ||
{ | ||
await Clients.Client(recipientConnectionId).SendAsync("SendUserToUser", senderUsername, recipientUsername, message); | ||
} | ||
} | ||
|
||
public override Task OnConnectedAsync() | ||
{ | ||
Console.WriteLine($"{Context.ConnectionId} connected"); | ||
var username = Context.GetHttpContext().Request.Query["username"]; | ||
_connectedUsers.TryAdd(Context.ConnectionId, username); | ||
Console.WriteLine($"{Context.ConnectionId}:${username} connected"); | ||
|
||
var userList = GetConnectedUsers(); | ||
Clients.Client(Context.ConnectionId).SendAsync("ReceiveConnectedUsers", userList); | ||
return base.OnConnectedAsync(); | ||
} | ||
|
||
public override async Task OnDisconnectedAsync(Exception e) | ||
{ | ||
Console.WriteLine($"Disconnected {e?.Message} {Context.ConnectionId}"); | ||
string username; | ||
_connectedUsers.TryRemove(Context.ConnectionId, out username); | ||
Console.WriteLine($"Disconnected {e?.Message} {Context.ConnectionId}:${username}"); | ||
await base.OnDisconnectedAsync(e); | ||
} | ||
public IEnumerable<string> GetConnectedUsers() | ||
{ | ||
return _connectedUsers.Values.Distinct(); | ||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -29,6 +29,15 @@ else | |
<span>You are connected as <b>@_username</b></span> | ||
<button class="btn btn-sm btn-warning ml-md-auto" @onclick="@DisconnectAsync">Disconnect</button> | ||
</div> | ||
|
||
<h2>Connected users:</h2> | ||
<ul> | ||
@foreach (var user in _connectedUsers) | ||
{ | ||
<li>@user</li> | ||
} | ||
</ul> | ||
|
||
// display messages | ||
<div id="scrollbox"> | ||
@foreach (var item in _messages) | ||
|
@@ -40,12 +49,18 @@ else | |
else | ||
{ | ||
<div class="@item.CSS"> | ||
@if (!string.IsNullOrWhiteSpace(item.RecieverUsername)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add <div class="user">From: @item.Username</div>
@if (!string.IsNullOrWhiteSpace(item.RecieverUsername))
{
<div class="user">To: @item.RecieverUsername</div>
}
<div class="msg">@item.Body</div> |
||
{ | ||
<div class="user">@item.RecieverUsername</div> | ||
} | ||
<div class="user">@item.Username</div> | ||
<div class="msg">@item.Body</div> | ||
</div> | ||
} | ||
} | ||
<hr /> | ||
<label for="recipientUsername">Send message to:</label> | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a <div id="sendto">
<label for="recipientUsername">Send message to:</label>
<input type="text" id="recipientUsername" @bind="_recipientUsername" />
</div> |
||
<input type="text" id="recipientUsername" @bind="_recipientUsername" /> | ||
<textarea class="input-lg" placeholder="enter your comment" @bind="@_newMessage"></textarea> | ||
<button class="btn btn-default" @onclick="@(() => SendAsync(_newMessage))">Send</button> | ||
</div> | ||
|
@@ -61,12 +76,18 @@ else | |
// on-screen message | ||
private string _message; | ||
|
||
// on-screen recipientUsername | ||
private string _recipientUsername; | ||
|
||
// new message input | ||
private string _newMessage; | ||
|
||
// list of messages in chat | ||
private List<Message> _messages = new List<Message>(); | ||
|
||
// list of messages in chat | ||
private List<string> _connectedUsers = new List<string>(); | ||
|
||
private string _hubUrl; | ||
private HubConnection _hubConnection; | ||
|
||
|
@@ -94,10 +115,17 @@ else | |
_hubUrl = baseUrl.TrimEnd('/') + BlazorChatSampleHub.HubUrl; | ||
|
||
_hubConnection = new HubConnectionBuilder() | ||
.WithUrl(_hubUrl) | ||
.WithUrl($"{_hubUrl}?username={_username}") | ||
.Build(); | ||
|
||
_hubConnection.On<IEnumerable<string>>("ReceiveConnectedUsers", (userList) => | ||
{ | ||
_connectedUsers = userList.ToList(); | ||
InvokeAsync(StateHasChanged); | ||
//StateHasChanged(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove this? |
||
}); | ||
_hubConnection.On<string, string>("Broadcast", BroadcastMessage); | ||
_hubConnection.On<string, string, string>("SendUserToUser", SendUserToUser); | ||
|
||
await _hubConnection.StartAsync(); | ||
|
||
|
@@ -110,14 +138,25 @@ else | |
} | ||
} | ||
|
||
private void SendUserToUser(string senderUsername, string recieverUsername, string message) | ||
{ | ||
bool isMine = senderUsername.Equals(_username, StringComparison.OrdinalIgnoreCase); | ||
var messageObj = new Message(senderUsername, message, isMine); | ||
messageObj.RecieverUsername = recieverUsername; | ||
_messages.Add(messageObj); | ||
|
||
// Inform blazor the UI needs updating | ||
InvokeAsync(StateHasChanged); | ||
} | ||
|
||
private void BroadcastMessage(string name, string message) | ||
{ | ||
bool isMine = name.Equals(_username, StringComparison.OrdinalIgnoreCase); | ||
|
||
_messages.Add(new Message(name, message, isMine)); | ||
|
||
// Inform blazor the UI needs updating | ||
StateHasChanged(); | ||
InvokeAsync(StateHasChanged); | ||
} | ||
|
||
private async Task DisconnectAsync() | ||
|
@@ -138,8 +177,14 @@ else | |
{ | ||
if (_isChatting && !string.IsNullOrWhiteSpace(message)) | ||
{ | ||
await _hubConnection.SendAsync("Broadcast", _username, message); | ||
|
||
if (string.IsNullOrWhiteSpace(_recipientUsername)) | ||
{ | ||
await _hubConnection.SendAsync("Broadcast", _username, message); | ||
} | ||
else | ||
{ | ||
await _hubConnection.SendAsync("SendUserToUser",_username, _recipientUsername, message); | ||
} | ||
_newMessage = string.Empty; | ||
} | ||
} | ||
|
@@ -154,6 +199,7 @@ else | |
} | ||
|
||
public string Username { get; set; } | ||
public string RecieverUsername { get; set; } | ||
public string Body { get; set; } | ||
public bool Mine { get; set; } | ||
|
||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about cache Dictionary<UserName, List>()? As always fetch by userId.