我想在ASP.NET MVC中使用SignalR创建实时聊天应用程序。我创建了这个,但问题是它是向连接到该服务器的所有用户发送消息。我只想在两个用户之间进行私聊。所以请帮帮我。这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
//this is ChatHub.cs file
namespace LiveChat
{
public class ChatHub : Hub
{
public override System.Threading.Tasks.Task OnConnected()
{
Clients.Caller.user(Context.User.Identity.Name);
return base.OnConnected();
}
public void send(string message)
{
Clients.Caller.message("You:" + message);
Clients.Others.message(Context.User.Identity.Name + ": " + message);
}
}}
//这是Startup类
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(LiveChat.Startup))]
namespace LiveChat
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
app.MapSignalR();
}
}
}
//This is my js
<script>
var hub = $.connection.chatHub;
hub.client.message = function (msg) {
$("#message").append("<li>" + msg + "</li>")
}
hub.client.user = function (msg) {
$("#user").append("<li>" + msg + "</li>")
}
$.connection.hub.start(function () {
$("#send").click(function () {
if ($("#txt").val() == "") {
return;
}
hub.server.send($("#txt").val());
$("#txt").val(" ");
});
$("#txt").keyup(function (event) {
if ($("#txt").val() == "") {
return;
}
if (event.keyCode == 13) {
hub.server.send($("#txt").val());
}
});
});
</script>
答案 0 :(得分:0)
您可以使用静态列表,该列表包含连接到集线器的所有客户端及其连接ID, 在发送消息时,您必须在集线器上显示文本和目标成员。而不是发送到特定的memeber。
将成员添加到OnConnected函数的列表中,客户端ID:
Context.clientID
发送给函数send中的特定客户端
var clientId = ""; // get from the static list by id you got
var scbscriber = Clients.Client(clientId);
scbscriber.message(text);
答案 1 :(得分:0)
new Vue({
el: '#appl',
router: Router,
render: h => h(App)
})
答案 2 :(得分:0)
您在这里结伴:
public void SendPrivateMessage(Messaging objMessaging)
{
var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message, DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };
Result objResult = objMessagingDAL.InsertMessage(objMessaging);
if (toNurse != null)
{
Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
}
Clients.Caller.ReceivePrivateMessage(chatObject);
}