很多的sns網站都提供了短訊息功能。而且,如果我們線上的話會很快的收到好友的短訊息。
這裡介紹一種用戶端的方法,簡單實現。
主要的表:
user
:Uid UName Password 三個欄位
Message
:Mid, SenderId, ReceiverId, State, Detail(SenderId和 ReceiverId)都是外鍵且對應user表中的Uid。
主要的思路很簡單:用js每隔五秒鐘發送一次ajax請求,擷取目前使用者在Message表中State為未讀取(這裡約定為數字1)且ReceverId為目前使用者ID的Message 記錄的數量。
頁面的代碼:
<%@ Page Language="C#" CodeBehind="Default.aspx.cs" Inherits="MIDemo._Default" %>
<!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>
<!-- 兩個js指令檔-->
<script type="text/javascript" src="SqlHelp/jquery-1.3.2.js"></script>
<script type="text/javascript" src="SqlHelp/GetMessageCount.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div style=" border-color:Green; border-style:solid; margin-top:100px; margin-left:300px; width:300px; height:50px; text-align:center;">
您有<input type="text" value="0" id="messageCount"/><a href="ShowMessage.aspx">條短訊息</a>
</div>
</form>
</body>
</html>
js代碼:這裡用到了Jquery架構,不再贅述,網上有很多的資料。
GetMessageCount.js
//------GetMessageCount.js Begin----------------------
if(!GetMessageCount){
var GetMessageCount = {};
}
$(document).ready(
function(){
GetMessageCount.FindMessage();
}
);
GetMessageCount.FindMessage = function(){
$.ajax({
//處理ajax請求
url:'FindNewMessage.ashx',
// 目前使用者的ID,這裡圖省事就省略了,直接寫死為 1,
//實際使用過程中可以從session中擷取 。。。。
data:{Uid:1},
cache: false,
//回呼函數返回未讀簡訊數目
success: function(response)
{
$('#messageCount').val(response);
},
error:function(data)
{
alert("載入失敗");
}
});
//每隔5 秒遞迴調用一次,重新整理未讀簡訊數目
window.setTimeout(GetMessageCount.FindMessage,5000);
}
//------GetMessageCount.js End----------------------
到了這裡,貼出處理ajax請求頁面的代碼,非常簡單
FindNewMessage.ashx
//----------------'FindNewMessage.ashx Begin
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace MIDemo
{
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class FindNewMessage : IHttpHandler
{