ASP.NET MVC4异步聊天室的示例代码

 更新时间:2021年9月22日 10:03  点击:1799

本文介绍了ASP.NET MVC4异步聊天室的示例代码,分享给大家,具体如下:

类图:

Domain层

IChatRoom.cs

using System;
using System.Collections.Generic;

namespace MvcAsyncChat.Domain
{
  public interface IChatRoom
  {
    void AddMessage(string message);
    void AddParticipant(string name);
    void GetMessages(
      DateTime since, 
      Action<IEnumerable<string>, DateTime> callback);
    void RemoveParticipant(string name);
  }
}
 

IMessageRepo.cs

using System;
using System.Collections.Generic;

namespace MvcAsyncChat.Domain
{
  public interface IMessageRepo
  {
    DateTime Add(string message);
    IEnumerable<string> GetSince(DateTime since);
  }
}

ICallbackQueue.cs

using System;
using System.Collections.Generic;

namespace MvcAsyncChat.Domain
{
  public interface ICallbackQueue
  {
    void Enqueue(Action<IEnumerable<string>, DateTime> callback);
    IEnumerable<Action<IEnumerable<string>, DateTime>> DequeueAll();
    IEnumerable<Action<IEnumerable<string>, DateTime>> DequeueExpired(DateTime expiry);
  }
}

ChatRoom.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MvcAsyncChat.Svcs;

namespace MvcAsyncChat.Domain
{
  public class ChatRoom : IChatRoom
  {
    readonly ICallbackQueue callbackQueue;
    readonly IDateTimeSvc dateTimeSvc;
    readonly IMessageRepo messageRepo;

    public ChatRoom(
      ICallbackQueue callbackQueue,
      IDateTimeSvc dateTimeSvc,
      IMessageRepo messageRepo)
    {
      this.callbackQueue = callbackQueue;
      this.dateTimeSvc = dateTimeSvc;
      this.messageRepo = messageRepo;
    }

    public void AddMessage(string message)
    {
      var timestamp = messageRepo.Add(message);

      foreach (var callback in callbackQueue.DequeueAll())
        callback(new[] { message }, timestamp);
    }

    public void AddParticipant(string name)
    {
      AddMessage(string.Format("{0} 已进入房间.", name));
    }

    public void GetMessages(
      DateTime since,
      Action<IEnumerable<string>, DateTime> callback)
    {
      var messages = messageRepo.GetSince(since);

      if (messages.Count() > 0)
        callback(messages, since);
      else
        callbackQueue.Enqueue(callback);
    }

    public void RemoveParticipant(string name)
    {
      AddMessage(string.Format("{0} left the room.", name));
    }
  }
}

InMemMessageRepo.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace MvcAsyncChat.Domain
{
  public class InMemMessageRepo : IMessageRepo
  {
    public InMemMessageRepo()
    {
      Messages = new List<Tuple<string, DateTime>>();
    }

    public IList<Tuple<string, DateTime>> Messages { get; private set; }

    public DateTime Add(string message)
    {
      var timestamp = DateTime.UtcNow;

      Messages.Add(new Tuple<string, DateTime>(message, timestamp));

      return timestamp;
    }

    public IEnumerable<string> GetSince(DateTime since)
    {
      return Messages
        .Where(x => x.Item2 > since)
        .Select(x => x.Item1);
    }
  }
}

CallbackQueue.cs

using System;
using System.Collections.Generic;
using System.Linq;

namespace MvcAsyncChat.Domain
{
  public class CallbackQueue : ICallbackQueue
  {
    public CallbackQueue()
    {
      Callbacks = new Queue<Tuple<Action<IEnumerable<string>, DateTime>, DateTime>>();
    }

    public Queue<Tuple<Action<IEnumerable<string>, DateTime>, DateTime>> Callbacks { get; private set; }

    public void Enqueue(Action<IEnumerable<string>, DateTime> callback)
    {
      Callbacks.Enqueue(new Tuple<Action<IEnumerable<string>, DateTime>, DateTime>(callback, DateTime.UtcNow));
    }

    public IEnumerable<Action<IEnumerable<string>, DateTime>> DequeueAll()
    {
      while (Callbacks.Count > 0)
        yield return Callbacks.Dequeue().Item1;
    }

    public IEnumerable<Action<IEnumerable<string>, DateTime>> DequeueExpired(DateTime expiry)
    {
      if (Callbacks.Count == 0)
        yield break;

      var oldest = Callbacks.Peek();
      while (Callbacks.Count > 0 && oldest.Item2 <= expiry)
      {
        yield return Callbacks.Dequeue().Item1;

        if (Callbacks.Count > 0)
          oldest = Callbacks.Peek();
      }
    }
  }
}

RequestModels文件夹实体类

EnterRequest.cs

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcAsyncChat.RequestModels
{
  public class EnterRequest
  {
    [DisplayName("名称")]
    [Required, StringLength(16), RegularExpression(@"^[A-Za-z0-9_\ -]+$", ErrorMessage="A name must be alpha-numeric.")]
    public string Name { get; set; }
  }
}

GetMessagesRequest.cs

using System;

namespace MvcAsyncChat.RequestModels
{
  public class GetMessagesRequest
  {
    public string since { get; set; }
  }
}

SayRequest.cs

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcAsyncChat.RequestModels
{
  public class SayRequest
  {
    [Required, StringLength(1024), DataType(DataType.MultilineText)]
    public string Text { get; set; }
  }
}

ResponseModels文件夹实体类

GetMessagesResponse.cs

using System;
using System.Collections.Generic;

namespace MvcAsyncChat.ResponseModels
{
  public class GetMessagesResponse
  {
    public string error { get; set; }
    public IEnumerable<string> messages { get; set; }
    public string since { get; set; }
  }
}

SayResponse.cs

using System;

namespace MvcAsyncChat.ResponseModels
{
  public class SayResponse
  {
    public string error { get; set; }
  }
}

ChatController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Async;
using MvcAsyncChat.Domain;
using MvcAsyncChat.RequestModels;
using MvcAsyncChat.ResponseModels;
using MvcAsyncChat.Svcs;

namespace MvcAsyncChat.Controllers
{
  public class ChatController : AsyncController
  {
    readonly IAuthSvc authSvc;
    readonly IChatRoom chatRoom;
    readonly IDateTimeSvc dateTimeSvc;

    public ChatController(
      IAuthSvc authSvc,
      IChatRoom chatRoom,
      IDateTimeSvc dateTimeSvc)
    {
      this.authSvc = authSvc;
      this.chatRoom = chatRoom;
      this.dateTimeSvc = dateTimeSvc;
    }

    [ActionName("enter"), HttpGet]
    public ActionResult ShowEnterForm()
    {
      if (User.Identity.IsAuthenticated)
        return RedirectToRoute(RouteName.Room);

      return View();
    }

    [ActionName("enter"), HttpPost]
    public ActionResult EnterRoom(EnterRequest enterRequest)
    {
      if (!ModelState.IsValid)
        return View(enterRequest);

      authSvc.Authenticate(enterRequest.Name);
      chatRoom.AddParticipant(enterRequest.Name);

      return RedirectToRoute(RouteName.Room);
    }

    [ActionName("room"), HttpGet, Authorize]
    public ActionResult ShowRoom()
    {
      return View();
    }

    [ActionName("leave"), HttpGet, Authorize]
    public ActionResult LeaveRoom()
    {
      authSvc.Unauthenticate();
      chatRoom.RemoveParticipant(User.Identity.Name);

      return RedirectToRoute(RouteName.Enter);
    }

    [HttpPost, Authorize]
    public ActionResult Say(SayRequest sayRequest)
    {
      if (!ModelState.IsValid)
        return Json(new SayResponse() { error = "该请求无效." });

      chatRoom.AddMessage(User.Identity.Name+" 说:"+sayRequest.Text);

      return Json(new SayResponse());
    }

    [ActionName("messages"), HttpPost, Authorize]
    public void GetMessagesAsync(GetMessagesRequest getMessagesRequest)
    {
      AsyncManager.OutstandingOperations.Increment();

      if (!ModelState.IsValid)
      {
        AsyncManager.Parameters["error"] = "The messages request was invalid.";
        AsyncManager.Parameters["since"] = null;
        AsyncManager.Parameters["messages"] = null;
        AsyncManager.OutstandingOperations.Decrement();
        return;
      }

      var since = dateTimeSvc.GetCurrentDateTimeAsUtc();
      if (!string.IsNullOrEmpty(getMessagesRequest.since))
        since = DateTime.Parse(getMessagesRequest.since).ToUniversalTime();

      chatRoom.GetMessages(since, (newMessages, timestamp) => 
      {
        AsyncManager.Parameters["error"] = null;
        AsyncManager.Parameters["since"] = timestamp;
        AsyncManager.Parameters["messages"] = newMessages;
        AsyncManager.OutstandingOperations.Decrement();
      });
    }

    public ActionResult GetMessagesCompleted(
      string error, 
      DateTime? since, 
      IEnumerable<string> messages)
    {
      if (!string.IsNullOrWhiteSpace(error))
        return Json(new GetMessagesResponse() { error = error });

      var data = new GetMessagesResponse();
      data.since = since.Value.ToString("o");
      data.messages = messages;

      return Json(data);
    }
  }
}

room.js

var since = "",
  errorCount = 0,
  MAX_ERRORS = 6;

function addMessage(message, type) {
  $("#messagesSection > td").append("<div class='" + (type || "") + "'>" + message + "</div>")
}

function showError(error) {
  addMessage(error.toString(), "error");
}

function onSayFailed(XMLHttpRequest, textStatus, errorThrown) {
  showError("An unanticipated error occured during the say request: " + textStatus + "; " + errorThrown);
}

function onSay(data) {
  if (data.error) {
    showError("An error occurred while trying to say your message: " + data.error);
    return;
  }
}

function setSayHandler() {
  $("#Text").keypress(function (e) {
    if (e.keyCode == 13) {
      $("#sayForm").submit();
      $("#Text").val("");
      return false;
    }
  });
}

function retryGetMessages() {
  if (++errorCount > MAX_ERRORS) {
    showError("There have been too many errors. Please leave the chat room and re-enter.");
  }
  else {
    setTimeout(function () {
      getMessages();
    }, Math.pow(2, errorCount) * 1000);
  }
}

function onMessagesFailed(XMLHttpRequest, textStatus, errorThrown) {
  showError("An unanticipated error occured during the messages request: " + textStatus + "; " + errorThrown);
  retryGetMessages();
}

function onMessages(data, textStatus, XMLHttpRequest) {
  if (data.error) {
    showError("An error occurred while trying to get messages: " + data.error);
    retryGetMessages();
    return;
  }

  errorCount = 0;
  since = data.since;

  for (var n = 0; n < data.messages.length; n++)
    addMessage(data.messages[n]);

  setTimeout(function () {
    getMessages();
  }, 0);
}

function getMessages() {
  $.ajax({
    cache: false,
    type: "POST",
    dataType: "json",
    url: "/messages",
    data: { since: since },
    error: onMessagesFailed,
    success: onMessages,
    timeout: 100000
  });
}

Chat视图文件夹

Enter.cshtml

@model MvcAsyncChat.RequestModels.EnterRequest

@{
  View.Title = "Enter";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Head {}

<tr id="enterSection">
  <td>
    <h2>[MVC聊天]是使用ASP.NET MVC 3的异步聊天室
    <table>
      <tr>
        <td class="form-container">
          <fieldset>
            <legend>进入聊天室</legend>
            @using(Html.BeginForm()) {
              @Html.EditorForModel()
              <input type="submit" value="Enter" />
            }
          </fieldset>
        </td>
      </tr>
    </table>
  </td>
</tr>

@section PostScript {
  <script>
    $(document).ready(function() {
      $("#Name").focus();  
    });
  </script>
}

Room.cshtml

@using MvcAsyncChat;
@using MvcAsyncChat.RequestModels;
@model SayRequest

@{
  View.Title = "Room";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

@section Head {
  <script src="@Url.Content("~/Scripts/room.js")"></script>
}

<tr id="messagesSection">
  <td></td>
</tr>
<tr id="actionsSection">
  <td>

    <label for="actionsList">操作:</label>
    <ul id="actionsList">
      <li>@Html.RouteLink("离开房间", RouteName.Leave)</li>
    </ul>
    @using (Ajax.BeginForm("say", new { }, new AjaxOptions() { 
      OnFailure = "onSayFailed", 
      OnSuccess = "onSay", 
      HttpMethod = "POST", }, new { id = "sayForm"})) {
      @Html.EditorForModel()
    }
  </td>
</tr>

@section PostScript {
  <script>
    $(document).ready(function() {
      $("#Text").attr("placeholder", "你说:");
      $("#Text").focus();
      setSayHandler();
      getMessages();
    });
  </script>
}

运行结果如图:

这里写图片描述

这里写图片描述

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章

  • ASP.NET购物车实现过程详解

    这篇文章主要为大家详细介绍了ASP.NET购物车的实现过程,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 在ASP.NET 2.0中操作数据之七十二:调试存储过程

    在开发过程中,使用Visual Studio的断点调试功能可以很方便帮我们调试发现程序存在的错误,同样Visual Studio也支持对SQL Server里面的存储过程进行调试,下面就让我们看看具体的调试方法。...2021-09-22
  • 美图秀秀制作隔离区聊天背景教程

    今天小编在这里就来给美图秀秀的这一款软件的使用者们来说下制作隔离区聊天背景的教程,各位想知道具体方法的,那么下面就快来跟着小编一起看一看吧。 给各位美图秀...2016-09-14
  • ASP.NET Core根据环境变量支持多个 appsettings.json配置文件

    这篇文章主要介绍了ASP.NET Core根据环境变量支持多个 appsettings.json配置文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • 记一次EFCore类型转换错误及解决方案

    这篇文章主要介绍了记一次EFCore类型转换错误及解决方案,帮助大家更好的理解和学习使用asp.net core,感兴趣的朋友可以了解下...2021-09-22
  • 深入分析C#中的异步和多线程

    这篇文章主要介绍了C#中异步和多线程的相关资料,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下...2021-01-16
  • C#多线程与异步的区别详解

    多线程和异步操作两者都可以达到避免调用线程阻塞的目的,从而提高软件的可响应性。甚至有些时候我们就认为多线程和异步操作是等同的概念。但是,多线程和异步操作还是有一些区别的。而这些区别造成了使用多线程和异步操作的时机的区别...2020-06-25
  • 详解C# Socket异步通信实例

    本篇文章主要介绍了C# Socket异步通信,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • JS异步的执行原理和回调详解

    这篇文章主要给大家介绍了关于JS异步的执行原理和回调的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-08
  • c# winform异步不卡界面的实现方法

    这篇文章主要给大家介绍了关于c# winform异步不卡界面的实现方法,文中通过示例代码介绍的非常详细,对大家学习或者使用c#具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧...2020-06-25
  • JQuery基于FormData异步提交数据文件

    这篇文章主要介绍了JQuery基于FormData异步提交数据文件,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-09-02
  • 详解ASP.NET Core 中基于工厂的中间件激活的实现方法

    这篇文章主要介绍了ASP.NET Core 中基于工厂的中间件激活的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-22
  • asp.net通过消息队列处理高并发请求(以抢小米手机为例)

    这篇文章主要介绍了asp.net通过消息队列处理高并发请求(以抢小米手机为例),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-09-22
  • ASP.NET单选按钮控件RadioButton常用属性和方法介绍

    RadioButton又称单选按钮,其在工具箱中的图标为 ,单选按钮通常成组出现,用于提供两个或多个互斥选项,即在一组单选钮中只能选择一个...2021-09-22
  • ASP.NET 2.0中的数据操作:使用两个DropDownList过滤的主/从报表

    在前面的指南中我们研究了如何显示一个简单的主/从报表, 该报表使用DropDownList和GridView控件, DropDownList填充类别,GridView显示选定类别的产品. 这类报表用于显示具有...2016-05-19
  • C# Socket编程实现简单的局域网聊天器的示例代码

    这篇文章主要介绍了C# Socket编程实现简单的局域网聊天器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • 如何使用PHP+jQuery+MySQL实现异步加载ECharts地图数据(附源码下载)

    ECharts地图主要用于地理区域数据的可视化,展示不同区域的数据分布信息,通过本文给大家介绍如何使用PHP+jQuery+MySQL实现异步加载ECharts地图数据,需要的朋友参考下吧...2016-02-26
  • ASP.NET中iframe框架点击左边页面链接 右边显示链接页面内容

    这篇文章主要介绍了ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容的实现代码,感兴趣的小伙伴们可以参考一下...2021-09-22
  • 创建一个完整的ASP.NET Web API项目

    ASP.NET Web API具有与ASP.NET MVC类似的编程方式,ASP.NET Web API不仅仅具有一个完全独立的消息处理管道,而且这个管道比为ASP.NET MVC设计的管道更为复杂,功能也更为强大。下面创建一个简单的Web API项目,需要的朋友可以参考下...2021-09-22
  • vue.js实现h5机器人聊天(测试版)

    这篇文章主要介绍了vue.js实现h5机器人聊天测试版,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-07-16