简单的信号器示例:访问https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio
然后更改chat.js
document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
var room = document.getElementById("room").value;
connection.invoke("SendMessage", user, message,room,false).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
document.getElementById("joinButton").addEventListener("click", function (event) {
var room = document.getElementById("room").value;
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message, room,true).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
使用以下代码编辑 ChatHub.cs 文件:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace SignalRChat.Hubs
{
public class ChatHub : Hub
{
public async Task SendMessage(string user, string message, string room, bool join)
{
if (join)
{
await JoinRoom(room).ConfigureAwait(false);
await Clients.Group(room).SendAsync("ReceiveMessage", user, " joined to " + room).ConfigureAwait(true);
}
else
{
await Clients.Group(room).SendAsync("ReceiveMessage", user, message).ConfigureAwait(true);
}
}
public Task JoinRoom(string roomName)
{
return Groups.AddToGroupAsync(Context.ConnectionId, roomName);
}
public Task LeaveRoom(string roomName)
{
return Groups.RemoveFromGroupAsync(Context.ConnectionId, roomName);
}
}
}
html示例:
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">Room</div>
<div class="col-4"><input type="text" id="room" /></div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-6">
<input type="button" id="joinButton" value="Join Room" />
</div>
</div>
</div>
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-2">User</div>
<div class="col-4"><input type="text" id="userInput" /></div>
</div>
<div class="row">
<div class="col-2">Message</div>
<div class="col-4"><input type="text" id="messageInput" /></div>
</div>
<div class="row"> </div>
<div class="row">
<div class="col-6">
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
<script src="~/js/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
signalr c# .net core3 聊天 室