【发布时间】:2013-12-13 12:10:00
【问题描述】:
我有一个基于 Asp.net MVC 和 SignalR 的简单聊天应用程序。我打算在每个“聊天室”中拥有一个 view
在这个应用程序中。每个“聊天室”都是一个信号组。我试图弄清楚服务器端如何知道
一个人在特定的view 中,然后将他/她的 connectionId 映射到该组。我有这样做的想法
在OnConnected() 任务中,当用户连接到聊天集时该任务会被击中。它看起来像这样:
public override async Task OnConnected()
{
if("view" == "Room1")
{
await Groups.Add(Context.ConnectionId, "Room1");
}
}
但是我如何获得"view"?也许有人知道这样做的不同方法?
以下是当前大部分视图的外观:
@model PagedList.IPagedList<ChatProj.Models.Message>
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<style>
ul {list-style-type:circle;}
</style>
<div class="container">
<div class="nano chat">
<div class="content">
<ul id="discussion">
</ul>
</div>
</div>
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" disabled="disabled" />
<input type="hidden" id="displayname" />
</div>
@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-1.1.3.js"></script>
<script src="~/Scripts/jquery.nanoscroller.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;
$(".nano").nanoScroller();
// 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>');
};
$(document).ready(function () {
$("#sendmessage").removeAttr("disabled");
$('#message').keypress(function (e) {
if (e.keyCode == 13)
$('#sendmessage').click();
});
});
// Get the user name and store it to prepend to messages.
// 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($('#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>
}
【问题讨论】:
-
为什么不用用户的
Session来代替呢?具有相同Session值的所有用户将被放置在同一个“房间”中。
标签: asp.net-mvc model-view-controller razor signalr