初学c# -- 学习笔记(一)
学习C#了,参考许多资料,一步步学习。这一段学习ajax的工作原理,参照其他例子写了web版的群聊小程序,全部文件代码也就不到300行,很简单。使用时先输入用户名,点确定,在下面输入框输入内容,上面显示框就可以看见内容,多找几台机子试试。编译时引用里面加上Microsoft.JScript,不加也可以,自己写一个Unescape。
编辑VS2015,.net 4.0,运行于IIS。
1.default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="ajax_test._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css">
body { font-size:12px; font-family:微软雅黑,宋体; background-color:#004d77; }
#input_msg { width:740px;height:145px;text-align:left;border:solid #F5F5F5;background:#F5F5F5;overflow-y:scroll;overflow-x:auto;word-wrap:break-word;padding:5px;z-Index:-1; }
#send_msg { width:740px;height:200px; overflow-y:scroll;overflow-x:hidden;overflow:auto;margin-top:0px;background:#fff;word-break:break-all;text-align:left; }
</style>
</head>
<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("send_msg").innerHTML = xmlhttp.responseText;
}
}
if (type == "get") { //取得数据信息
xmlhttp.open("POST", "http://127.0.0.1/receive.aspx?type=get" + "&uid=" + escape(username), 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), 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);
}
setscroll(); //滚动保持最底部
setTimeout("loadXMLDoc('get','')", 1000); //1秒执行一次
}
}
function InitUser (uname)
{
username = uname; //初始化用户名
}
function html2Escape(sHtml) { //转码
return sHtml.replace(/[<>&"]/g, function (c) { return { '<': '<', '>': '>', '&': '&', '"': '"' }[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 setscroll() //设置滚动到底部
{
var sendObj = document.getElementById("send_msg");
if (msg_Len !== sendObj.innerHTML.length) //内容长度改变,设置滚动条
{
sendObj.scrollTop += sendObj.scrollHeight;
msg_Len = sendObj.innerHTML.length; //更新长度
}
}
</script>
<body>
<form id="Ajax_Test" runat="server">
<div>
<table id="table_fence" cellspacing="0" cellpadding="0" width="100%" border="0" style="background-color: #004d77;" runat="server">
</table>
</div>
</form>
</body>
</html>
2.default.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace ajax_test
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Table Table_Frame;
Table_Frame = new Table();
Table_Frame.HorizontalAlign = HorizontalAlign.Center;
Table_Frame.Width = 900;
Table_Frame.CellPadding = 0;
Table_Frame.CellSpacing = 0;
TableRow Table_FrameRow = new TableRow();
TableCell Table_FrameCell = new TableCell();
Table_FrameCell.Text = "<div id='send_msg'></div>"; //消息显示框
Table_FrameRow.Cells.Add(Table_FrameCell);
Table_Frame.Rows.Add(Table_FrameRow);
Table_FrameRow = new TableRow();
Table_FrameCell = new TableCell();
Table_FrameCell.Text = "<br/><br/>";
Table_FrameRow.Cells.Add(Table_FrameCell);
Table_Frame.Rows.Add(Table_FrameRow);
Table_FrameRow = new TableRow();
Table_FrameCell = new TableCell();
Table_FrameCell.Text = //登录框,要先登录再做其他的
@"<input id='in_Name' type='text'>
<input id='in_Iden' type='button' value='确定'
onclick='InitUser(document.getElementById(""in_Name"").value);
loadXMLDoc(""get"","""");'>";
Table_FrameRow.Cells.Add(Table_FrameCell);
Table_Frame.Rows.Add(Table_FrameRow);
Table_FrameRow = new TableRow();
Table_FrameCell = new TableCell();
Table_FrameCell.Text = "<div id='input_msg' contentEditable=true></div>"; //录入信息框
Table_FrameRow.Cells.Add(Table_FrameCell);
Table_Frame.Rows.Add(Table_FrameRow);
Table_FrameRow = new TableRow();
Table_FrameCell = new TableCell();
Table_FrameCell.Text = //发送信息按钮
@"<input type='button' id='btnSend' value='提交'
onclick='loadXMLDoc(""send"",document.getElementById(""input_msg"").innerHTML);'>";
Table_FrameRow.Cells.Add(Table_FrameCell);
Table_Frame.Rows.Add(Table_FrameRow);
System.Web.UI.HtmlControls.HtmlTableRow HtmlTableRow = new System.Web.UI.HtmlControls.HtmlTableRow();
System.Web.UI.HtmlControls.HtmlTableCell HtmlCell = new System.Web.UI.HtmlControls.HtmlTableCell();
HtmlCell.Controls.Add(Table_Frame);
HtmlTableRow.Controls.Add(HtmlCell);
table_fence.Rows.Add(HtmlTableRow);
}
}
}
3.msglist.cs(没aspx文件)
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ajax_test
{
public class MsgList
{
public static ArrayList msglist = new ArrayList(); //全部发送的内容
public static ArrayList userlist = new ArrayList(); //发送的用户名
public static int idNum = 0; //消息总数
}
}
4.receive.cs(aspx文件就保留第一行,其他删掉)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Caching;
using System.Collections;
using System.Text;
namespace ajax_test
{
public partial class Receive : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); //不使用浏览器缓存
ArrayList vlist = new ArrayList(); //引用类,内容
ArrayList ulist = 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); //所有用户名写入缓存
vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
for (int i = 0; i < nowId + 1; i++) //将全部内容放入字符串
{
if ((string)ulist[i] == uid) //如果是本人,加粗显示,也可定义左右方向显示
{
strCount = strCount + ulist[i] + ":" + "<b>" +vlist[i]+"</b>";
}
else
{
strCount = strCount + ulist[i] + ":" + vlist[i];
}
strCount = strCount + "<br/><br/>";
}
MsgList.idNum++;
Cache.Insert("num_info", MsgList.idNum); //序号总数
}
///////////////////////////////////////////////////////////////////////////////////////////////
if (type == "get") //取得全部消息
{
vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
for (int i = 0; i < nowId; i++) //将全部内容放入字符串
{
if ((string)ulist[i] == uid) //如果是本人,加粗显示,也可定义左右方向显示
{
strCount = strCount + ulist[i] + ":" + "<b>"+vlist[i]+"</b>";
}
else
{
strCount = strCount + ulist[i] + ":" + vlist[i];
}
strCount = strCount + "<br/><br/>";
}
}
Response.Write(strCount); //显示到内容框里面
Response.Flush();
Response.End();
}
}
}