Skip to content
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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 25 additions & 2 deletions samples/BlazorChat/BlazorChatSampleHub.cs
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;
Expand All @@ -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>();
Copy link
Contributor

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.


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;
Copy link
Contributor

Choose a reason for hiding this comment

The 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();
}
}
}
54 changes: 50 additions & 4 deletions samples/BlazorChat/Pages/ChatRoom.razor
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -40,12 +49,18 @@ else
else
{
<div class="@item.CSS">
@if (!string.IsNullOrWhiteSpace(item.RecieverUsername))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add From and To for easy understand and optimize order like below?

<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>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a <div> to wrap this Send section, so won't break the rendering.

<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>
Expand All @@ -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;

Expand Down Expand Up @@ -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();
Copy link
Contributor

Choose a reason for hiding this comment

The 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();

Expand All @@ -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()
Expand All @@ -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;
}
}
Expand All @@ -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; }

Expand Down