1.建立儲存發言的訊息資料表 chatrooms 只要2個欄位 id 和 c_content
id必須設定識別值種子和識別值增量都為 1
2.聊天室的程式3支程式 Default.aspx(聊天室頁面) , Insert.aspx(新增發言) , GetJSON.aspx(取得聊天訊息)
首先新增聊天室的首頁Default.aspx ,畫面上只需要1個DIV顯示發言列表,1個Input輸入框,1個Buttn送出鍵
<form id="form1"> <div> <div id="msg_list" style="width: 600px; height: 300px; overflow-x: hidden; overflow-y: auto; background-color: white;"> </div> <input name="msg" id="msg" type="text" style="width: 500px;" /> <input name="send" id="send" type="button" value="送出" /> </div> </form>
3. 接下來新增Insert.aspx將接收到的訊息寫入資料庫,只需要將程式寫在Insert.aspx.cs中
protected void Page_Load(object sender, EventArgs e) { //宣告sqlDataSource SqlDataSource sqlDataSource = new SqlDataSource(); //建立資料庫的連結字串(寫在web.config) sqlDataSource.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; //取得聊天訊息(GET) String c_content = Request.QueryString["msg"]; //將訊息寫入資料庫 sqlDataSource.InsertCommand = "Insert into chatrooms (c_content) values ('" + c_content + "')"; int aff_row = sqlDataSource.Insert(); sqlDataSource.Dispose(); }
4. 然後新增 GetJSON.aspx 因為這一頁是用來產生JSON所以頁面上不能有其他HTML語法 ,所以將頁面清掉只留下一行
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetJSON.aspx.cs" Inherits="GetJSON" %>
5. 因為要使用到 JavaScriptSerializer 類別來將我們取得的聊天訊息做JSON序列化,所以要先在 GetJSON.aspx.cs 加上命名空間 System.Web.Script.Serialization
using System.Web.Script.Serialization;
6. 接下來就開始寫取得聊天資訊並做JSON序列化的程式
public partial class GetJSON : System.Web.UI.Page { //建立class物件 public class MsgItem { public int id { get; set; } public string content { get; set; } } protected void Page_Load(object sender, EventArgs e) { LoadDatabase(); } private void LoadDatabase() { //建立MsgItem的List List<MsgItem> MsgList = new List<MsgItem>(); SqlConnection Conn = new SqlConnection(); //宣告SqlConnection並實體化 SqlCommand cmd = new SqlCommand(); //宣告SqlCommand並實體化 string strSQL; SqlDataReader dr = null; try { //設定Connection String並且開啟Connection Conn.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; Conn.Open(); //取得聊天室資料 strSQL = "SELECT * FROM chatrooms"; cmd.Connection = Conn; cmd.CommandText = strSQL; dr = cmd.ExecuteReader(); if (dr.HasRows) { //將資料庫中的資料add到List中 while (dr.Read()) { int cid = (int)dr["id"]; string c_content = dr["c_content"].ToString(); MsgList.Add(new MsgItem() { id = cid, content = c_content }); } } else { HttpContext.Current.Response.End(); } dr.Close(); //關閉 DataReader } catch (Exception ex) { } finally { if (dr != null) { dr.Close(); dr.Dispose(); } if (cmd != null) { cmd.Cancel(); cmd.Dispose(); } if (Conn != null) { Conn.Close(); Conn.Dispose(); } } //JSON序列化 JavaScriptSerializer objSerializer = new JavaScriptSerializer(); Response.Write(objSerializer.Serialize(MsgList)); } }
7. 再回到 Default.aspx 在head之間寫jQuery程式送出訊息和每2秒取得JSON資訊並顯示在畫面上(jquery.js 請自行到官方網站下載)
<script type="text/javascript" src="jquery.js"></script> <script language="javascript"> //發送訊息 function sendMsg() { $.get( "Insert.aspx", { msg: $("#msg").val() , msgtime : new Date().getTime() }, function () { getMsg(); $("#msg").val(""); //清空輸入框 } ); } var g_id = 0; //保存上次取得最後訊息id //取得訊息 function getMsg() { $.getJSON("GetJSON.aspx", (function () { if ("\v" == "v") return { id: g_id, rand: Math.random() }; // IE else return { id: g_id }; })(), function (json) { if (json != null) { var arr = json.length; for (var i = 0; i < arr; i++) { if (g_id < json[i].id) { g_id = json[i].id; //將最新的id儲存 var msg = []; var content = decodeURIComponent(json[i].content).replace(/&/g, "&").replace(/</g, "⪫").replace(/>/g, ">"); msg.push("<div>"); msg.push(content); msg.push("</div>"); } if (msg) { $('#msg_list').append(msg.join("")); $('#msg_list').scrollTop($('#msg')[0].scrollHeight); //將捲軸移到最下方 } } } }); } //每兩秒從資料庫取一次資料 setInterval("getMsg()", 2000); </script>
8. 最後在送出Button加上onclick
<input name="send" Id="send" type="button" onclick="sendMsg()" value="送出">
全站熱搜