ajax网页聊天室

ajax网页聊天室,接收信息递归循环。

        $(function () {
            $("#btn1").click(function () {
                $.post("MsgAJAX.ashx", { "action": "send", "msg": $("#txtMsg").val() },
                    //发送完成清空
                     function (data) { $("#txtMsg").val(""); }
                     );
            });

            recvMsg();
        });

        var recvMsg = function () {
            $.post("MsgAJAX.ashx", { "action": "recv" }, function (data) {
                $("#ul1").append("<li>" + data + "</li>");
                recvMsg();
            });
        };
   public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            if (action == "send")
            {
                string msg = context.Request["msg"];
                
                MsgQueue.Instance.Push(msg);
            }
            else if (action == "recv")
            {
                string msg = MsgQueue.Instance.Take();
                context.Response.Write(msg);
            }
            else
            {
                throw new Exception("错误的action");
            }
        }
    public class MsgQueue
    {
        private List<string> list = new List<string>();

        public readonly static MsgQueue Instance = new MsgQueue();

        private MsgQueue()
        {
        }

        public void Push(string msg)
        {
            list.Add(msg);
        }

        public string Take()
        {
            StringBuilder sb = new StringBuilder();
            while (list.Count <= 0)
            {
                Thread.Sleep(10);
            }
            foreach (string msg in list)
            {
                sb.AppendLine(msg);
            }
            list.Clear();
            return sb.ToString();
        }
    }

如果是多用户,还需要一个静态列表存用户,ajax静态页没有session,可以用请求ip作为用户标识。

因为没有数据库,消息队列的消息是共享的,所以必须等待所有用户取回消息,才可以移除一条消息。

继续接收也必须等待其他所有用户请求接收完毕,可以增加一个超时自动踢出用户的机制。

原文地址:https://www.cnblogs.com/tgdjw/p/4606876.html