实时聊天 -模板代码






4.83/5 (11投票s)
如何使用 C# ASP.NET + jQuery/AJAX 创建 Web 实时聊天
引言
我一直在寻找用于 .NET 应用程序的实时聊天功能代码。(那种可以与公司技术人员交谈的类型,而不是即时通讯工具)。我没有找到任何东西,所以我编写了一些基础代码来实现它。
背景
这使用了 jQuery 和 Ajax 调用。还使用了 http://json.org/json2.js 将字符串编码为 json。
性能影响:它只是轮询服务器以获取消息(因为它不是客户端应用程序)。
另外:其中包含许多将替换为数据库连接的虚拟代码。我目前使用 Session.ClientLCID
来唯一标识会话。如果您有用户登录,您应该用用户 ID 替换它。
(代码注释不够。我会尝试改进它,但由于我不确定是否有人会查看此内容……我可能只是让您自己弄清楚。)
代码看起来怎么样?
所以,HTML 非常简单。
<input type="hidden" id="LastUpdateId" value="0" />
<input type="hidden" id="ConversationId" value="0" />
<div id="result"></div>
<textarea id="message"></textarea>
<input type="button" id="send" value="send" />
C# 也不太糟糕
[WebMethod]
public static IEnumerable<IMailUpdate>
GetUpdates(int ConversationId, int LastUpdateId) {
Conversation c = DAC.GetConversation(ConversationId);
CheckConversationAccess(c);
return c.GetUpdatesAfter(LastUpdateId);
}
[WebMethod]
public static string SendUpdate(int ConversationId, string update) {
Conversation c = DAC.GetConversation(ConversationId);
CheckConversationAccess(c);
MailUpdate item = new MailUpdate();
item.Author = SessionStateSink.IsTechnician ?
"Technician" : "Client";//you should populate this from user information.
item.CssClass = SessionStateSink.IsTechnician ?
"tech" : "client";//you can leave this or find a different way of handling it.
item.TimeStamp = DateTime.Now;
item.Message = update;
item.Save();
return "";
}
jQuery / AJAX 才是真正有趣的地方
//Sending the data!
$.ajax({
timeout: 15000,
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8", dataType: 'json',
url: 'chat.aspx/SendUpdate',
data: '{ConversationId:' + $("#ConversationId")[0].value +
',update:' + JSON.stringify(message) + '}'
});
//Receiving the Data!
$.ajax({
timeout: 15000,
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: 'json',
url: 'chat.aspx/GetUpdates',
data: '{ConversationId:' + $("#ConversationId")[0].value +
',LastUpdateId:' + $("#LastUpdateId")[0].value + '}',
success: chat_populateItems
});
//Populating the Data! (Data displayed here is
//reflective of the custom IMailMessage interface)
function chat_populateItems(data) {
for (var index = 0; index < data.d.length; index++) {
var item = data.d[index];
if ($('#update' + item.UpdateId).length == 0) {
var text = "(" + item.DateString + ") " +
item.Author + ": " + item.Message;
$('#result').append("<div id='update" + item.Id +
"' class='" + item.CssClass + "' />").children(":last").text(text);
}
}
if (data.d.length > 0) {
$("#LastUpdateId")[0].value = data.d[data.d.length - 1].Id;
}
}
注意:为了使代码更易于阅读,我删除了上面的错误函数(等)。
如果您有任何问题或意见,请发表!