使用asp.net与长连接技术制作网页聊天工具(初步)

来源:互联网 发布:西安 长安 知乎 编辑:程序博客网 时间:2024/04/30 10:04

点击打开链接前言:

这个只是我初步做到能发送接收消息,其他功能没有的,适合用来学习。

有些多余的代码我没删,让学习的人能感受下我思考的过程,看起了很简单,但实际我做了挺多的尝试,花了两天时间才做到现在这样的效果。

操作流程:

第一步

运行项目,打开/Client/WebIM.aspx或者/Default.aspx(同样会跳转到WebIM.aspx),输入账号。和你聊天的人的两个框输入相反即可。
如图:

第二步:

登陆后页面改变如图:

就可以和你的好友聊天了,聊天效果




代码:

文件分布图:



MessageService.cs:

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using System.Threading;using WebIMModel;/// <summary>///MessageService 的摘要说明/// </summary>[WebService(Namespace = "http://tgnet.cn/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 [System.Web.Script.Services.ScriptService]public class MessageService : System.Web.Services.WebService{    WebIMEntities entity = new WebIMEntities();    Mutex mutex = new Mutex();    public MessageService()    {        //如果使用设计的组件,请取消注释以下行         //InitializeComponent();     }    /// <summary>    ///监听消息,在没新消息的时候挂起,在有新消息的时候返回消息内容    /// </summary>    /// <param name="sentUserID"></param>    /// <param name="receiverUserID"></param>    /// <returns></returns>    [WebMethod]    public string WaitMessage(string sentUserID, string receiverUserID)    {        string message = "";        string strSessionName = sentUserID + "-" + receiverUserID;        // mutex = new Mutex(false, strSessionName);        // mutex.WaitOne(10000);        //挂起线程        try        {            int i = 0;            while (i < 20)            {                message += GetMessage(Convert.ToInt64(sentUserID), Convert.ToInt64(receiverUserID));                Thread.Sleep(1000);                if (!string.IsNullOrEmpty(message))                {                    return "1" + message;                }                i++;            }            return "0";        }        catch (Exception)        {            return "0";        }    }    /// <summary>    /// 获得消息内容    /// </summary>    /// <param name="sentUserID"></param>    /// <param name="receiverUserID"></param>    /// <returns></returns>    private string GetMessage(long sentUserID, long receiverUserID)    {        var messageList = from m in entity.IM_Message                          where m.isRead == false && m.receiverUserID.Value == receiverUserID && m.sentUserID.Value == sentUserID                          select m;        string strMessage = "";        foreach (IM_Message item in messageList)        {            strMessage += string.Format("{0}:{1}   {2}<br />", item.sentUserID, item.content, item.sentTime);            item.isRead = true;        }        entity.SaveChanges();        return strMessage;    }    /// <summary>    ///发送消息,注意要将与之对应的消息监听线程启动    /// </summary>    /// <param name="sentUserID"></param>    /// <param name="receiverUserID"></param>    /// <returns></returns>    [WebMethod]    public int SentMessage(string sentUserID, string receiverUserID, string content)    {        string strSessionName = sentUserID + "-" + receiverUserID;        int isUpdated = 0;        try        {            //TODO 恢复相应的线程WaitMessage            //Mutex m = Mutex.OpenExisting(strSessionName);            //m.ReleaseMutex();            //this.mutex.ReleaseMutex();        }        catch (WaitHandleCannotBeOpenedException ex)        {            //TODO 用户不存在的情况业务逻辑        }        catch { }        finally        {            if (UpdateDB(sentUserID, receiverUserID, content))            {                isUpdated = 1;            }        }        return isUpdated;    }    /// <summary>    /// 更新数据库    /// </summary>    /// <param name="sentUserID"></param>    /// <param name="receiverUserID"></param>    /// <param name="content">消息内容</param>    /// <returns></returns>    private bool UpdateDB(string sentUserID, string receiverUserID, string content)    {        IM_Message m = new IM_Message();        try        {            m.sentUserID = Convert.ToInt64(sentUserID);            m.receiverUserID = Convert.ToInt64(receiverUserID);            m.content = content;            m.isRead = false;            m.sentTime = DateTime.Now;            entity.IM_Message.AddObject(m);            entity.SaveChanges();            return true;        }        catch (Exception)        {            return false;        }    }}

WebIM.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebIM.aspx.cs" Inherits="Client_WebIM" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title>    <script src="../JS/jquery.js" type="text/javascript"></script>    <script type="text/javascript">        var myUserID;        var orderUserID;        $(function () {            $("#divMessageDialog").hide();            $("#btlogin").click(function () {                myUserID = $("#txtMyUserID").val();                orderUserID = $("#txtOrderUserID").val();                $("#divLogin").hide();                $("#divMessageDialog").show();                WaitMessage();            });        })        function WaitMessage() {            $.post(                "/System/MessageService.asmx/WaitMessage",                { sentUserID: orderUserID, receiverUserID: myUserID },                function (data) {                    if (data.text.substring(0, 1) == 1) {                        //有消息的处理                        $("#history").html($("#history").html() + "<br />" + data.text.substring(1));                    } else {                        //没消息的处理                    }                    WaitMessage();                }            );        }        function SentMessage() {            $.post(                "/System/MessageService.asmx/SentMessage",                { sentUserID: myUserID, receiverUserID: orderUserID, content: $("#txaMessage").val() },                function (data) {                    if (data.text.substring(0, 1)) {                        //发送成功的处理                        $("#history").html($("#history").html() + "<br />" + "你说:" + $("#txaMessage").val() + new Date().toLocaleDateString());                        $("#txaMessage").val("");                    }                    else {                        $("#history").html($("#history").html() + "<br />" + "你说:" + $("#txaMessage").val() + new Date().toLocaleDateString() + "发送不成功");                    }                }            )        }    </script></head><body>    <form id="form1" runat="server">    <div id="divLogin">        <table>            <tr>                <th colspan="2">                    欢迎使用TGWebIM                </th>            </tr>            <tr>                <td>                    请输入你的账号:                </td>                <td>                    <input id="txtMyUserID" />                </td>            </tr>            <tr>                <td>                    请输入好友的账号:                </td>                <td>                    <input id="txtOrderUserID" />                </td>            </tr>            <tr>                <td>                    <input type="button" id="btlogin" value="登陆" />                </td>                <td>                    <input type="button" id="reset" value="重置" />                </td>            </tr>        </table>    </div>    <div id="divMessageDialog">        <table>            <tr>                <th>                    欢迎使用TGWebIM                </th>            </tr>            <tr>                <td id="history" style="height: 200px">                </td>            </tr>            <tr>                <td>                    <textarea cols="100" id="txaMessage" rows="3"></textarea>                </td>            </tr>            <tr>                <td><input type="button" id="btSentMessage" onclick="SentMessage()" value="发送" /></td>            </tr>        </table>    </div>    </form></body></html>


数据库访问时用entity frameword





资源下载地址:资源下载