我正在使用asp.net Signal R库..如何让我只与一个人聊天而不是群聊,是否可以使用asp.net signal r库?
我还希望看到聊天记录而不保存数据库是否可以将聊天记录广泛转换为特定用户?
///班级文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace Chat.Hubs
{
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
}
}
///视图
@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="@Url.Content("~/Scripts/jquery.signalR-1.1.3.min.js")"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
答案 0 :(得分:1)
要向特定用户发送消息,您可以使用Clients.Client方法,例如:
Clients.Client(someClientsConnectionId).foo();
要检索客户端连接ID,您可以将其捕获到Context.ConnectionId。因此,您的集线器可能看起来像这样跟踪用户并专门发送给他们。
public MyHub: Hub
{
private static readonly ConcurrentDictionary<string, string> _users = new ConcurrentDictionary<string, string>();
...
public void Join(string userName)
{
_users[theUsersUserName] = Context.ConnectionId;
}
public void SendToUser(string userName, string message)
{
Clients.Client(_users[userName]).foo(message).
}
...
}