Hub
public class StreamHub : Hub
{
public ChannelReader<string> ReadLogStream()
{
var channel = Channel.CreateUnbounded<string>();
_ = WriteFileLine(channel.Writer);
return channel.Reader;
}
private async Task WriteFileLine(ChannelWriter<string> writer)
{
using (var streamReader = new StreamReader(Directory.GetCurrentDirectory() + "/logs/server.log"))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
await writer.WriteAsync(line);
await Task.Delay(TimeSpan.FromSeconds(2));
}
writer.TryComplete();
}
}
}
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRCharSample.Hubs
{
[Authorize]
public class UserChatHub: Hub
{
public async Task SendMessage(string toUserName, string message)
{
await Clients.User(toUserName).SendAsync("ReceiveMessage", $"{DateTime.Now}--{Context.UserIdentifier}--{message}");
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div>
UserName:<input type="text" id="userInput" />
Message:<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send" />
</div>
<ul id="messagesList"></ul>
<script src="http://localhost:57634/lib/jquery/dist/jquery.js"></script>
<script src="http://localhost:57634/lib/signalr.min.js"></script>
<script>
var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:57634/chatHub").build();
connection.on("ReceiveMessage", function (user, message) {
var msg = user + " says " + message;
var li = document.createElement("li");
li.textContent = msg;
document.getElementById("messagesList").appendChild(li);
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
</script>
</body>
</html>
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRCharSample.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, DateTime.Now + "--" + message);
}
public Task SendMessageToCaller(string message)
{
return Clients.Caller.SendAsync("ReceiveMessage",message);
}
public Task SendMessageToGroups(string message)
{
List<string> groups = new List<string>() { "Group1","Group2" };
return Clients.Groups(groups).SendAsync("ReceiveMessage", message);
}
public override async Task OnConnectedAsync()
{
await Groups.AddToGroupAsync(Context.ConnectionId, "Group1");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "Group1");
await base.OnDisconnectedAsync(exception);
}
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRCharSample.Hubs
{
public class CustomUserIdProvider : IUserIdProvider
{
public string GetUserId(HubConnectionContext connection)
{
//return connection.GetHttpContext().Request.Query["userid"];
return connection.User?.FindFirst("UserName")?.Value;
}
}
}
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SignalRCharSample.Hubs
{
public class GroupChatHub: Hub
{
public async Task AddToGroup(string groupName)
{
await Groups.AddToGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has joined the group {groupName}.");
}
public async Task RemoveFromGroup(string groupName)
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
await Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId} has left the group {groupName}.");
}
public Task SendMessageToGroup(string groupName, string message)
{
return Clients.Group(groupName).SendAsync("Send", $"{Context.ConnectionId}: {message}");
}
public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
}
}