asp.net练习①——Application聊天室

已经好几年没写过代码,重新练习起代码,在这做做笔记备忘。

aspx页面js代码:

<script type="text/javascript">
        function showMsg()
        {
            //定时刷新获取聊天内容
            var data = "{}";
            $.ajax({
                type: "POST",
                datatype: "json",
                contentType: "application/json; charset=utf-8",
                url: "WebService1.asmx/GetMessageContent",
                success: function (result) {
                    var msgdiv = document.getElementById("MessageShowDiv");
                    msgdiv.innerHTML = "";
                    msgdiv.innerHTML = result.d;
                    //保持滚动条在最下面
                    msgdiv.scrollTop = msgdiv.scrollHeight;
                }
            })
        }
        var timer1 = window.setInterval("showMsg()", 2000);
        //window.clearInterval(timer1)


        function showOnlineUsers()
        {
            var users = document.getElementById("OnlineUsersShow");
            $.ajax({
                type: "POST",
                datatype: "json",
                contentType: "application/json;charset=utf-8",
                url: "WebService1.asmx/GetOnlineUsers",
                success: function (result)
                {
                    users.innerHTML = "";
                    var str = result.d.substring(0,result.d.lastIndexOf("|")).split("|");
                    var userStr = "";
                    $.each(str, function (i, val) {
                        userStr += val + "<br/>";
                    })
                    users.innerHTML = userStr;
                }
            })
        }
        var timer2 = window.setInterval("showOnlineUsers()", 10000);
        //window.clearInterval(timer2)


        function sendMsg()
        {
            var txt = document.getElementById("txtMessage");
            if (txt.value.length > 0) {
                var MsgData = "{Msg:'" + $("#txtMessage").val() + "'}";
                $.ajax({
                    data : MsgData,
                    type : "POST",
                    datatype: "json",
                    contentType: "application/json; charset=utf-8",
                    url: "WebService1.asmx/SendMsg",
                    success: function (result) {
                        if (result.d == "true")
                        {
                            showMsg();
                            txt.value = "";
                        }
                        else if (result.d == "OutTime") {
                            alert("登录超时,请重新登录!");
                            window.location.href = '_login.aspx';
                        }
                        else {
                            alert("通讯发送错误:" + result.d);
                        }
                    },
                    error: function (e) {
                        alert(e.d);
                    }
                });
            }
            else {
                alert("请输入内容再发送...");
            }
        }
    </script>

  

  

asmx代码:

[WebMethod (Description ="获取聊天记录",EnableSession = true)]
        public string GetMessageContent()
        {
            if (Application["Message"] == null)
            {
                return "当前无聊天信息。";
            }
            int length = Convert.ToInt32(Session["MessageLength"]);
            return Application["Message"].ToString().Substring(length);
        }

        [WebMethod(Description = "发送聊天内容", EnableSession = true)]
        public string SendMsg(string Msg)
        {
            //验证用户是否登录超时
            if (Session["UserName"] == null)
            {
                return "OutTime";
            }
            try
            {
                //用户 [时间]:内容
                string message = Msg.Trim();
                string username = Session["UserName"].ToString();
                string datenow = DateTime.Now.ToLongTimeString();
                string msg = username + " [" + datenow + "] :" + message + "<br/>";
                Application.Lock();
                Application["Message"] = Application["Message"].ToString() + msg;
                Application.UnLock();
                return "true";
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        [WebMethod(Description = "获取在线用户")]
        public string GetOnlineUsers()
        {
            if (Application["OnlinePersons"] == null)
            {
                return "";
            }
            return Application["OnlinePersons"].ToString();
        }

  登录后cs代码:

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //记录用户名
            Session["username"] = username.Value;
            //增加在线用户
            Application.Lock();
            Application["online"] += username.Value + "|";
            Application.UnLock();
            //记录登录时存在的聊天信息长度,只显示登录后发生的聊天信息
            Session["messageLength"] = 0;
            Application.Lock();
            Session["messageLength"] = Application["Message"].ToString().Length;
            Application.UnLock();
            //跳转页面
            Response.Redirect("_showMessage.aspx");
        }

  

源代码链接:http://pan.baidu.com/s/1o7WuTGu