在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → c#实现ajax 聊天窗口实例

c#实现ajax 聊天窗口实例

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.66M
  • 下载次数:56
  • 浏览次数:557
  • 发布时间:2016-11-28
  • 实例类别:C#语言基础
  • 发 布 人:tzjtzj18
  • 文件格式:.rar
  • 所需积分:2
 相关标签: Ajax 实例 C# c

实例介绍

【实例简介】

c#实现web ajax通讯的例子,无第三方插件、脚本,无ajax.js类库,c#实现。运行IE9以上,IIS,.net 4.0,代码其他.net版本也可以编译通过。非IE浏览器用极速模式浏览,因为兼容模式支持IE的版本太低,除火狐外,其他浏览器均正常显示。例子包括:自定义滚动条、css3绘图、c#实现ajax原理等。做了“”频道“部分,其他部分原理相同就没做了。最右侧未放功能,空白。为了便于学习,没用数据库,全在缓存中进行数据交互,把代码里127.0换成你的地址。多找几台机子,配好iis,试试。

【实例截图】

【核心代码】

Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); //不使用浏览器缓存
            string[] Msg_bubble = new string[3];
            string[] Msg_bubbleRight = new string[3];

  
            ArrayList vlist = new ArrayList(); //引用类,内容
            ArrayList ulist = new ArrayList(); //引用类,用户名
            ArrayList tlist = new ArrayList(); //引用类,内容
            ArrayList klist = new ArrayList(); //引用类,内容
            /////////////////////////////////////
            string strCount = ""; //存放消息
            int nowId = 0; //消息总数

            string type = Request.QueryString["type"].ToString(); //取得传递页面参数“type”
            string uid = Microsoft.JScript.GlobalObject.unescape(Request.QueryString["uid"].ToString()); //解码

            if (Cache.Get("num_info") != null) //取得消息总数
            {
                nowId = (int)Cache.Get("num_info"); //从缓存中取得数目
            }

            if (type == "send") //发送消息
            {
                string Msg = Request.Form["msg"].ToString(); //取得post传递的内容
                Msg = HttpUtility.HtmlDecode(Msg); //解码
               Msg = Msg.Replace("\r\n", "<br/>");

                MsgList.msglist.Add(Msg); //将内容添加到MsgList类中
                Cache.Insert("msg_info", MsgList.msglist); //所有内容写入缓存

                MsgList.userlist.Add(uid); //将当前用户名添加到MsgList类中
                Cache.Insert("user_info", MsgList.userlist); //所有用户名写入缓存

                MsgList.timelist.Add(DateTime.Now.ToString("H:m")); //time
                Cache.Insert("time_info", MsgList.timelist); //time

                MsgList.takelist.Add(Request.QueryString["taker"].ToString()); //对象
                Cache.Insert("take_info", MsgList.takelist); //time

                vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
                ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
                tlist = (ArrayList)Cache.Get("time_info"); //缓存取得时间
                klist = (ArrayList)Cache.Get("take_info"); //缓存取得对象

                for (int i = 0; i < nowId 1; i ) //将全部内容放入字符串
                {
                    if ((string)klist[i] == Request.QueryString["taker"].ToString())
                    {
                        if ((string)ulist[i] == uid) //如果是本人
                        {
                            strCount = strCount Msg_bubbleRight[0] "<span style='color:#bbb'>" ulist[i] "&nbsp;&nbsp;" tlist[i] "</span>" Msg_bubbleRight[1] vlist[i] Msg_bubbleRight[2];
                        }
                        else
                        {
                            strCount = strCount Msg_bubble[0] "<span style='color:#bbb'>" ulist[i] "&nbsp;&nbsp;" tlist[i] "</span>" Msg_bubble[1] vlist[i] Msg_bubble[2];
                        }
                        strCount = strCount "<br/>";
                    }
                }
                MsgList.idNum ;
                Cache.Insert("num_info", MsgList.idNum); //序号总数
            }
            ///////////////////////////////////////////////////////////////////////////////////////////////
            if (type == "get") //取得全部消息
            {
                vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
                ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
                tlist = (ArrayList)Cache.Get("time_info"); //缓存取得全部用户
                klist = (ArrayList)Cache.Get("take_info"); //缓存取得对象

                for (int i = 0; i < nowId; i ) //将全部内容放入字符串
                {
                    if ((string)klist[i] == Request.QueryString["taker"].ToString())
                    {
                        if ((string)ulist[i] == uid) //如果是本人
                        {
                            strCount = strCount Msg_bubbleRight[0] "<span style='color:#bbb'>" ulist[i] "&nbsp;&nbsp;" tlist[i] "</span>" Msg_bubbleRight[1] vlist[i] Msg_bubbleRight[2];
                        }
                        else
                        {
                            strCount = strCount Msg_bubble[0] "<span style='color:#bbb;margin-right:20px;'>" ulist[i] "&nbsp;&nbsp;" tlist[i] "</span>" Msg_bubble[1] vlist[i] Msg_bubble[2];
                        }
                        strCount = strCount "<br/>";
                    }
                }
            }
            Response.Write(strCount); //显示到内容框里面




aspx中定义

<script type="text/javascript">
    var username = null, msg_Len = 0; //设置用户、显示内容长度

    function loadXMLDoc(type,sendHtml)
    {
        var xmlhttp;
        if (username != null)
        {
            if (window.XMLHttpRequest)  {
                xmlhttp = new XMLHttpRequest();
            }
            else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("message-take").innerHTML = xmlhttp.responseText;
                }
            }
            if (type == "get") { //取得数据信息
                xmlhttp.open("POST", "http://127.0.0.1/receive.aspx?type=get" "&uid=" escape(username) "&taker=" document.getElementById('take-class').value, true); //传递页面
                xmlhttp.send();
            } else if (type == "send") { //发送数据信息
                var nowTime = new Date().getTime();
                xmlhttp.open("POST", "http://127.0.0.1/receive.aspx?type=send&timeStamp=" nowTime "&uid=" escape(username) "&taker=" document.getElementById('take-class').value, true);
                sendHtml = html2Escape(sendHtml); //转码,能显示html格式
                var queryString = "msg=" escape(sendHtml); //发送的内容
                xmlhttp.setRequestHeader("Content-Length", queryString.lenght); //发送的内容长度
                xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //发送的内容编码
                xmlhttp.send(queryString);
            }
           ScrolltoBottom(); //滚动保持最底部
            setTimeout("loadXMLDoc('get','')", 1000); //1秒执行一次
        }
    }
    
    function loadXMLNum() {
        var xmlhttp_num;
        if (username != null) {
            if (window.XMLHttpRequest) {
                xmlhttp_num = new XMLHttpRequest();
            }
            else {
                xmlhttp_num = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp_num.onreadystatechange = function () {
                if (xmlhttp_num.readyState == 4 && xmlhttp_num.status == 200) {
                    document.getElementById("num_flush").innerHTML = xmlhttp_num.responseText;
                }
            }
            xmlhttp_num.open("POST", "http://127.0.0.1/infonum.aspx", true);
            xmlhttp_num.send(null);
            setTimeout("loadXMLNum()", 2000); //2秒执行一次
        }
    }

    function InitUser(uname)
    {
        username = uname; //初始化用户名
    }

    function html2Escape(sHtml) { //转码
        return sHtml.replace(/[<>&"]/g, function (c) { return { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]; });
    }

    function escape2Html(str) { //转码
        var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
        return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
    }

    function ScrolltoBottom() //设置滚动条到底部
    {
        var oContainer = document.getElementById("take-message-scroll"),
            osend_msg = document.getElementById("message-take"),
            oScroll_track = document.getElementById("ScrollBar-TakeTrack"),
            oScroll_arrow = document.getElementById("ScrollBar-TakeArrow");

        if (msg_Len !== osend_msg.innerHTML.length) { //内容长度改变,设置滚动条
            if (osend_msg.scrollHeight >=450) {
                oScroll_arrow.style.top = (oScroll_track.offsetHeight - oScroll_arrow.offsetHeight) 'px';
                osend_msg.style.top = -(osend_msg.offsetHeight - oContainer.offsetHeight) 'px';
            } else {
                oScroll_arrow.style.top = 0 "px";
                osend_msg.style.top = 0 "px";
            }
            msg_Len = osend_msg.innerHTML.length; //更新长度
        }
    }

    function Scroll_Event(mainObj,sendObj,Track,Arrow) //鼠标滚动事件
    {
        var oContainer = document.getElementById(mainObj),
            osend_msg = document.getElementById(sendObj),
            oScroll_track = document.getElementById(Track),
            oScroll_arrow = document.getElementById(Arrow);

        addEvent(osend_msg, 'mousewheel', mousewheel);
        addEvent(osend_msg, 'DOMMouseScroll', mousewheel);
        addEvent(oScroll_track, 'mousewheel', mousewheel);
        addEvent(oScroll_track, 'DOMMouseScroll', mousewheel);

        oScroll_arrow.onmousedown = function (e) {
            e = e || event;
            var disY = e.clientY - this.offsetTop;
            if (oScroll_arrow.setCapture) {
                oScroll_arrow.onmousemove = fnMove;
                oScroll_arrow.onmouseup = fnUp;
                oScroll_arrow.setCapture();
            } else {
                document.onmousemove = fnMove;
                document.onmouseup = fnUp;
            }
            function fnMove(ev) {
                ev = ev || event;
                var t = ev.clientY - disY;
                setTop(t);
            };
            function fnUp() {
                this.onmousemove = null;
                this.onmouseup = null;
                if (this.releaseCapture) {
                    this.releaseCapture();
                }
            };
            return false;
        };

        function setTop(t) {
            var down = oScroll_track.offsetHeight - oScroll_arrow.offsetHeight;
            if (t < 0) {
                t = 0;
            } else if (t > down) {
                t = down
            }
            oScroll_arrow.style.top = t 'px';
            var scale = t / down;
            osend_msg.style.top = -(osend_msg.offsetHeight - oContainer.offsetHeight) * scale 'px';
        }

        function addEvent(obj, oEvent, fn) {
            if (obj.attachEvent) {
                obj.attachEvent('on' oEvent, fn);
            } else {
                obj.addEventListener(oEvent, fn, false);
            }
        }

        function mousewheel(e) {
            var ev = e || event, bDown = false;
            bDown = ev.wheelDelta ? ev.wheelDelta < 0 : ev.detail > 0;
            if (bDown) {
                setTop(oScroll_arrow.offsetTop 10);
            } else {
                setTop(oScroll_arrow.offsetTop - 10);
            }
            if (e.preventDefault) {
                e.preventDefault();
            }
            return false;
        }
    }

    function InsertMessageInfo(obj,html,taker,num) {
        document.getElementById(obj).innerHTML = html "<span class=message-tool-ing style=float:right>" getNowFormatDate() "<span>";
        Scroll_Event("take-message-scroll", "message-take", "ScrollBar-TakeTrack", "ScrollBar-TakeArrow");
        clear_txt('abcEdit_mid');
        document.getElementById('abcEdit_mid').contentEditable = true;
        document.getElementById('take-class').value = taker;
        document.getElementById('num-class').value = num;
        loadXMLDoc('get', '');///
    }

    ...........................................

...........................................





标签: Ajax 实例 C# c

实例下载地址

c#实现ajax 聊天窗口实例

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警