想要将值插入到自动编号(或者说是标识列,IDENTITY)中去,需要设定 SET IDENTITY_INSERT 示例: 1.首先建立一个有标识列的表:CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40)) 2.尝试在表中做以下操作:INSERT INTO products (id, product) VALUES(3, 'garden shovel') 结果会导致错误:“当 IDENTITY_INSERT 设置为 OFF 时,不能向表 'products' 中的标识列插入显式值。” 3.改用:SET IDENTITY_INSERT products ONINSERT INTO products (id, product) VALUES(1, 'garden shovel') 返回正确。 4.建立另外一个表products2,尝试相同插入操作:CREATE TABLE products2 (id int IDENTITY PRIMARY KEY, product varchar(40)) 然后执行:SET IDENTITY_INSERT products2 ONINSERT INTO products2 (id, product) VALUES(1, 'garden shovel') 导致错误:“表 'material.dbo.products' 的 IDENTITY_INSERT 已经为 ON。无法对表 'products2' 执行 SET 操作。” 改为执行:SET IDENTITY_INSERT products OFFSET IDENTITY_INSERT products2 ONINSERT INTO products2 (id, product) VALUES(2, 'garden shovel') 执行通过。 5.尝试以下操作:SET IDENTITY_INSERT […]
View Details一、准备知识点: 1.对文件操作,先引用两个命名空间:using System.IO;(操作文件)、using Sysetem.Text;(操作文本) 2.创建文本文件:(1)创建文件名和文件内容(相当于新建文本文档)(2)创建StreamWriter对象,创建一个某某格式的文件(3)将内容写入数据流WriteLine (4)关闭StreamWrite对象.Close() 方法一:直接创建一个StreamWriter对象 string filename = TextBox1.Text string filecontent= TextBox2.Text StreamWriter sw =File.CreatText(Server.MapPath("~/txt/"+ filename +".txt")); sw.WriteLine(filecontent); sw.Close(); Response.Write("<script>alert('已经成功新建了一个’+ filename +'.txt,并添加了数据')</script>") 方法二:在创建StreamWriter对象之前先创建一个FileStream(文件流)对象,并在最后关闭它。 string filename = TextBox1.Text string filecontent= TextBox2.Text FileStream fs = new FileStream(Server.MapPath("~/txt/"+ filename + ".txt")),FileMode.Create,FileAccess.Write); //文件流fs的路径、文件打开方式:创建和写操作 StreamWriter sw = new StreamWriter(fs,Encoding.Default); //文件流fs和浏览器默认编码类型 sw.WriteLine(filecontent); sw.Close(); fs.Close(); Response.Write("<script>alert('成功新建了一个’+ filename +'.txt,并添加了数据')</script>") 3.读取文本文本: 方法一:直接使用File.ReadAllText(文件路径,编码方式) TextBox1.Text=File.ReadAllText(Server.MapPath("~/txt/**.txt"),Encoding.Default); 方法二:使用StreamReader对象以File.OpenText(文件路径)读取文件数据以及使用StreamBuilder对象的Append属性来添加读取文件的数据(UTF-8规范读取的数据) StreamReader sr = File.OpenText(Server.MapPath("~/txt/**.txt")); StreamBuilder sb = new StreamBuilder(); while(!sr.EndOfStream) //如果数据不到最后一行,继续添加(循环语句) { sb.Append(sr.ReadLine() +"<br>");} sr.Close(); 方法三:使用StreamBuilder对象的Append属性添加从StreamReader对象那里读取的数据流,与前一种方法不同的是,这次用到了FileStream的File.Open方法取代了File.OpenText(文件路径)的方法(GB2312规范读取数据) StreamBuilder sb = new StreamBuilder(); FileStream fs = File.Open(Server.MapPath("~/txt/**.txt"),FileMode.Open,FileAccess.Read); StreamReader sr = new StreamReader(fs,Encoding.Default); […]
View Details一.设置web.config相关选项先启用窗体身份验证和默认登陆页,如下。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">authentication </span><span style="color: #ff0000">mode</span><span style="color: #0000ff">="Forms"</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"><</span><span style="color: #800000">forms </span><span style="color: #ff0000">loginUrl</span><span style="color: #0000ff">="default.aspx"</span><span style="color: #0000ff">></</span><span style="color: #800000">forms</span><span style="color: #0000ff">></span><span style="color: #000000"><br /></span><span style="color: #0000ff"></</span><span style="color: #800000">authentication</span><span style="color: #0000ff">></span></div> |
设置网站可以匿名访问,如下
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">authorization</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"><</span><span style="color: #800000">allow </span><span style="color: #ff0000">users</span><span style="color: #0000ff">="*"</span><span style="color: #ff0000"> </span><span style="color: #0000ff">/></span><span style="color: #000000"><br /></span><span style="color: #0000ff"></</span><span style="color: #800000">authorization</span><span style="color: #0000ff">></span></div> |
然后设置跟目录下的admin目录拒绝匿名登陆,如下。注意这个小节在System.Web小节下面。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">location </span><span style="color: #ff0000">path</span><span style="color: #0000ff">="admin"</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"><</span><span style="color: #800000">system.web</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"><</span><span style="color: #800000">authorization</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"><</span><span style="color: #800000">deny </span><span style="color: #ff0000">users</span><span style="color: #0000ff">="?"</span><span style="color: #0000ff">></</span><span style="color: #800000">deny</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"></</span><span style="color: #800000">authorization</span><span style="color: #0000ff">></span><span style="color: #000000"><br /> </span><span style="color: #0000ff"></</span><span style="color: #800000">system.web</span><span style="color: #0000ff">></span><span style="color: #000000"><br /></span><span style="color: #0000ff"></</span><span style="color: #800000">location</span><span style="color: #0000ff">></span></div> |
把http请求和发送的编码设置成GB2312,否则在取查询字符串的时候会有问题,如下。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">globalization </span><span style="color: #ff0000">requestEncoding</span><span style="color: #0000ff">="gb2312"</span><span style="color: #ff0000"> responseEncoding</span><span style="color: #0000ff">="gb2312"</span><span style="color: #ff0000"> </span><span style="color: #0000ff">/></span></div> |
设置session超时时间为1分钟,并启用cookieless,如下。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">sessionState </span><span style="color: #ff0000">mode</span><span style="color: #0000ff">="InProc"</span><span style="color: #ff0000"> cookieless</span><span style="color: #0000ff">="true"</span><span style="color: #ff0000"> timeout</span><span style="color: #0000ff">="1"</span><span style="color: #ff0000"> </span><span style="color: #0000ff">/></span></div> |
为了启用页面跟踪,我们先启用每一页的trace,以便我们方便的调试,如下。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff"><</span><span style="color: #800000">trace </span><span style="color: #ff0000">enabled</span><span style="color: #0000ff">="true"</span><span style="color: #ff0000"> requestLimit</span><span style="color: #0000ff">="1000"</span><span style="color: #ff0000"> pageOutput</span><span style="color: #0000ff">="true"</span><span style="color: #ff0000"> traceMode</span><span style="color: #0000ff">="SortByTime"</span><span style="color: #ff0000"> localOnly</span><span style="color: #0000ff">="true"</span><span style="color: #ff0000"> </span><span style="color: #0000ff">/></span></div> |
二.设置Global.asax文件 处理Application_Start方法,实例化一个哈希表,然后保存在Cache里
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff">protected</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> Application_Start(Object sender, EventArgs e)<br />{<br /> Hashtable h</span><span style="color: #000000">=</span><span style="color: #0000ff">new</span><span style="color: #000000"> Hashtable();<br /> Context.Cache.Insert(</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">,h);<br />}</span></div> |
在Session_End方法里调用LogoutCache()方法,方法源码如下
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /></span><span style="color: #808080">///</span><span style="color: #008000"> 清除Cache里当前的用户,主要在Global.asax的Session_End方法和用户注销的方法里调用<br /></span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> LogoutCache()<br />{<br /> Hashtable h</span><span style="color: #000000">=</span><span style="color: #000000">(Hashtable)Context.Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">];<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000">(h</span><span style="color: #000000">!=</span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> {<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000">(h[Session.SessionID]</span><span style="color: #000000">!=</span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> h.Remove(Session.SessionID);<br /> Context.Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">]</span><span style="color: #000000">=</span><span style="color: #000000">h;<br /> }<br />}</span></div> |
三.设置相关的登陆和注销代码 登陆前调用PreventRepeatLogin()方法,这个方法可以防止用户重复登陆,如果上次用户登陆超时大于1分钟,也就是关闭了所有admin目录下的页面达到60秒以上,就认为上次登陆的用户超时,你就可以登陆了,如果不超过60秒,就会生成一个自定义异常。在Cache["online"]里保存了一个哈西表,哈西表的key是当前登陆用户的SessionID,而Value是一个ArrayList,这个ArrayList有两个元素,第一个是用户登陆的名字第二个元素是用户登陆的时间,然后在每个admin目录下的页刷新页面的时候会更新当前登陆用户的登陆时间,而只admin目录下有一个页打开着,即使不手工向服务器发送请求,也会自动发送一个请求更新登陆时间,下面我在页面基类里写了一个函数来做到这一点,其实这会增加服务器的负担,但在一定情况下也是一个可行的办法.
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /></span><span style="color: #808080">///</span><span style="color: #008000"> 防止用户重复登陆,在用户将要身份验证前使用<br /></span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #008000"><br /></span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="name"></span><span style="color: #008000">要验证的用户名字</span><span style="color: #808080"></param></span><span style="color: #808080"><br /></span><span style="color: #0000ff">private</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> PreventRepeatLogin(</span><span style="color: #0000ff">string</span><span style="color: #000000"> name)<br />{<br /> Hashtable h </span><span style="color: #000000">=</span><span style="color: #000000"> (Hashtable)Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">];<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (h </span><span style="color: #000000">!=</span><span style="color: #000000"> </span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> {<br /> IDictionaryEnumerator e1 </span><span style="color: #000000">=</span><span style="color: #000000"> h.GetEnumerator();<br /> </span><span style="color: #0000ff">bool</span><span style="color: #000000"> flag </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #0000ff">false</span><span style="color: #000000">;<br /> </span><span style="color: #0000ff">while</span><span style="color: #000000"> (e1.MoveNext())<br /> {<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> ((</span><span style="color: #0000ff">string</span><span style="color: #000000">)((ArrayList)e1.Value)[</span><span style="color: #800080">0</span><span style="color: #000000">] </span><span style="color: #000000">==</span><span style="color: #000000"> name)<br /> {<br /> flag </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #0000ff">true</span><span style="color: #000000">;<br /> </span><span style="color: #0000ff">break</span><span style="color: #000000">;<br /> }<br /> }<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (flag)<br /> {<br /> TimeSpan ts </span><span style="color: #000000">=</span><span style="color: #000000"> System.DateTime.Now.Subtract(Convert.ToDateTime(((ArrayList)e1.Value)[</span><span style="color: #800080">1</span><span style="color: #000000">]));<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (ts.TotalSeconds </span><span style="color: #000000"><</span><span style="color: #000000"> </span><span style="color: #800080">60</span><span style="color: #000000">)<br /> </span><span style="color: #0000ff">throw</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> oa.cls.MyException(</span><span style="color: #800000">"</span><span style="color: #800000">对不起,你输入的账户正在被使用中,如果你是这个账户的真正主人,请在下次登陆时及时的更改你的密码,因为你的密码极有可能被盗窃了!</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> </span><span style="color: #0000ff">else</span><span style="color: #000000"><br /> h.Remove(e1.Key);<br /> }<br /> }<br /> </span><span style="color: #0000ff">else</span><span style="color: #000000"><br /> {<br /> h </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> Hashtable();<br /> }<br /> ArrayList al </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> ArrayList();<br /> al.Add(name);<br /> al.Add(System.DateTime.Now);<br /> h[Session.SessionID] </span><span style="color: #000000">=</span><span style="color: #000000"> al;<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">] </span><span style="color: #000000">==</span><span style="color: #000000"> </span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> {<br /> Context.Cache.Insert(</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">, h);<br /> }<br /> </span><span style="color: #0000ff">else</span><span style="color: #000000"><br /> Cache[</span><span style="color: #800000">"</span><span style="color: #800000">Online</span><span style="color: #800000">"</span><span style="color: #000000">] </span><span style="color: #000000">=</span><span style="color: #000000"> h;<br />}</span></div> |
用户注销的时候调用上面提到LogoutCache()方法 四.设置admin目录下的的所有页面的基类
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff">using</span><span style="color: #000000"> System;<br /></span><span style="color: #0000ff">using</span><span style="color: #000000"> System.Web;<br /></span><span style="color: #0000ff">using</span><span style="color: #000000"> System.Web.UI;<br /></span><span style="color: #0000ff">using</span><span style="color: #000000"> System.Web.UI.WebControls;<br /></span><span style="color: #0000ff">using</span><span style="color: #000000"> System.Web.UI.HtmlControls;<br /></span><span style="color: #0000ff">using</span><span style="color: #000000"> System.Collections;<br /></span><span style="color: #0000ff">namespace</span><span style="color: #000000"> oa.cls<br />{<br /> </span><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">class</span><span style="color: #000000"> MyBasePage : System.Web.UI.Page<br /> {<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 获取本页是否在受保护目录,我这里整个程序在OA的虚拟目录下,受保护的目录是admin目录<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">protected</span><span style="color: #000000"> </span><span style="color: #0000ff">bool</span><span style="color: #000000"> IsAdminDir<br /> {<br /> </span><span style="color: #0000ff">get</span><span style="color: #000000"><br /> {<br /> </span><span style="color: #0000ff">return</span><span style="color: #000000"> Request.FilePath.IndexOf(</span><span style="color: #800000">"</span><span style="color: #800000">/oa/admin</span><span style="color: #800000">"</span><span style="color: #000000">) </span><span style="color: #000000">==</span><span style="color: #000000"> </span><span style="color: #800080">0</span><span style="color: #000000">;<br /> }<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 防止session超时,如果超时就注销身份验证并提示和转向到网站默认页<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">private</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> PreventSessionTimeout()<br /> {<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000">(</span><span style="color: #000000">!</span><span style="color: #0000ff">this</span><span style="color: #000000">.IsAdminDir) </span><span style="color: #0000ff">return</span><span style="color: #000000">;<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000">(Session[</span><span style="color: #800000">"</span><span style="color: #800000">User_Name</span><span style="color: #800000">"</span><span style="color: #000000">]</span><span style="color: #000000">==</span><span style="color: #0000ff">null</span><span style="color: #000000">&&</span><span style="color: #0000ff">this</span><span style="color: #000000">.IsAdminDir)<br /> { <br /> System.Web.Security.FormsAuthentication.SignOut();<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.Alert(</span><span style="color: #800000">"</span><span style="color: #800000">登陆超时</span><span style="color: #800000">"</span><span style="color: #000000">,Request.ApplicationPath)<br /> }<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 每次刷新本页面的时候更新Cache里的登陆时间选项,在下面的OnInit方法里调用.<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">private</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> UpdateCacheTime()<br /> {<br /> Hashtable h </span><span style="color: #000000">=</span><span style="color: #000000"> (Hashtable)Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">];<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (h </span><span style="color: #000000">!=</span><span style="color: #000000"> </span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> {<br /> ((ArrayList)h[Session.SessionID])[</span><span style="color: #800080">1</span><span style="color: #000000">] </span><span style="color: #000000">=</span><span style="color: #000000"> DateTime.Now;<br /> }<br /> Cache[</span><span style="color: #800000">"</span><span style="color: #800000">Online</span><span style="color: #800000">"</span><span style="color: #000000">] </span><span style="color: #000000">=</span><span style="color: #000000"> h;<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 在跟踪里输出一个HashTable的所有元素,在下面的OnInit方法里调用.以便方便的观察缓存数据<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="myList"></param></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">private</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> TraceValues(Hashtable myList)<br /> {<br /> IDictionaryEnumerator myEnumerator </span><span style="color: #000000">=</span><span style="color: #000000"> myList.GetEnumerator();<br /> </span><span style="color: #0000ff">int</span><span style="color: #000000"> i </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #800080">0</span><span style="color: #000000">;<br /> </span><span style="color: #0000ff">while</span><span style="color: #000000"> (myEnumerator.MoveNext())<br /> {<br /> Context.Trace.Write(</span><span style="color: #800000">"</span><span style="color: #800000">onlineSessionID</span><span style="color: #800000">"</span><span style="color: #000000"> </span><span style="color: #000000">+</span><span style="color: #000000"> i, myEnumerator.Key.ToString());<br /> ArrayList al </span><span style="color: #000000">=</span><span style="color: #000000"> (ArrayList)myEnumerator.Value;<br /> Context.Trace.Write(</span><span style="color: #800000">"</span><span style="color: #800000">onlineName</span><span style="color: #800000">"</span><span style="color: #000000"> </span><span style="color: #000000">+</span><span style="color: #000000"> i, al[</span><span style="color: #800080">0</span><span style="color: #000000">].ToString());<br /> Context.Trace.Write(</span><span style="color: #800000">"</span><span style="color: #800000">onlineTime</span><span style="color: #800000">"</span><span style="color: #000000"> </span><span style="color: #000000">+</span><span style="color: #000000"> i, al[</span><span style="color: #800080">1</span><span style="color: #000000">].ToString());<br /> TimeSpan ts </span><span style="color: #000000">=</span><span style="color: #000000"> System.DateTime.Now.Subtract(Convert.ToDateTime(al[</span><span style="color: #800080">1</span><span style="color: #000000">].ToString()));<br /> Context.Trace.Write(</span><span style="color: #800000">"</span><span style="color: #800000">当前的时间和此登陆时间间隔的秒数</span><span style="color: #800000">"</span><span style="color: #000000">, ts.TotalSeconds.ToString());<br /> i</span><span style="color: #000000">++</span><span style="color: #000000">;<br /> }<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 弹出信息并返回到指定页<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="msg"></span><span style="color: #008000">弹出的消息</span><span style="color: #808080"></param></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="url"></span><span style="color: #008000">指定转向的页面</span><span style="color: #808080"></param></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">protected</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> Alert(</span><span style="color: #0000ff">string</span><span style="color: #000000"> msg, </span><span style="color: #0000ff">string</span><span style="color: #000000"> url)<br /> {<br /> </span><span style="color: #0000ff">string</span><span style="color: #000000"> scriptString </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #800000">"</span><span style="color: #800000"><script language=JavaScript>alert(\</span><span style="color: #800000">""</span><span style="color: #800000"> + msg + </span><span style="color: #800000">"</span><span style="color: #000000">\</span><span style="color: #800000">"</span><span style="color: #800000">);location.href=\</span><span style="color: #800000">""</span><span style="color: #800000"> + url + </span><span style="color: #800000">"</span><span style="color: #000000">\</span><span style="color: #800000">"</span><span style="color: #800000"></script></span><span style="color: #800000">"</span><span style="color: #000000">;<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (</span><span style="color: #000000">!</span><span style="color: #0000ff">this</span><span style="color: #000000">.IsStartupScriptRegistered(</span><span style="color: #800000">"</span><span style="color: #800000">alert</span><span style="color: #800000">"</span><span style="color: #000000">))<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.RegisterStartupScript(</span><span style="color: #800000">"</span><span style="color: #800000">alert</span><span style="color: #800000">"</span><span style="color: #000000">, scriptString);<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 为了防止常时间不刷新页面造成会话超时,这里写一段脚本,每隔一分钟向本页发送一个请求以维持会话不被超时,这里用的是xmlhttp的无刷新请求<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 这个方法也在下面的OnInit方法里调用<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">protected</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> XmlReLoad()<br /> {<br /> System.Text.StringBuilder htmlstr </span><span style="color: #000000">=</span><span style="color: #000000"> </span><span style="color: #0000ff">new</span><span style="color: #000000"> System.Text.StringBuilder();<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"><SCRIPT LANGUAGE=\</span><span style="color: #800000">"</span><span style="color: #000000">JavaScript\</span><span style="color: #800000">"</span><span style="color: #800000">></span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000">function GetMessage(){</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"> var xh=new ActiveXObject(\</span><span style="color: #800000">"</span><span style="color: #000000">Microsoft.XMLHTTP\</span><span style="color: #800000">"</span><span style="color: #800000">);</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"> xh.open(\</span><span style="color: #800000">"</span><span style="color: #0000ff">get</span><span style="color: #000000">\</span><span style="color: #800000">"</span><span style="color: #800000">,window.location,false);</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"> xh.send();</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"> window.setTimeout(\</span><span style="color: #800000">"</span><span style="color: #000000">GetMessage()\</span><span style="color: #800000">"</span><span style="color: #800000">,60000);</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000">}</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000">window.onload=GetMessage();</span><span style="color: #800000">"</span><span style="color: #000000">);<br /> htmlstr.Append(</span><span style="color: #800000">"</span><span style="color: #800000"></SCRIPT> </span><span style="color: #800000">"</span><span style="color: #000000">);<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (</span><span style="color: #000000">!</span><span style="color: #0000ff">this</span><span style="color: #000000">.IsStartupScriptRegistered(</span><span style="color: #800000">"</span><span style="color: #800000">xmlreload</span><span style="color: #800000">"</span><span style="color: #000000">))<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.RegisterStartupScript(</span><span style="color: #800000">"</span><span style="color: #800000">alert</span><span style="color: #800000">"</span><span style="color: #000000">, htmlstr.ToString());<br /> }<br /> </span><span style="color: #0000ff">override</span><span style="color: #000000"> </span><span style="color: #0000ff">protected</span><span style="color: #000000"> </span><span style="color: #0000ff">void</span><span style="color: #000000"> OnInit(EventArgs e)<br /> {<br /> </span><span style="color: #0000ff">base</span><span style="color: #000000">.OnInit(e);<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.PreventSessionTimeout();<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.UpdateCacheTime();<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.XmlReLoad();<br /> </span><span style="color: #0000ff">if</span><span style="color: #000000"> (</span><span style="color: #0000ff">this</span><span style="color: #000000">.Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">] </span><span style="color: #000000">!=</span><span style="color: #000000"> </span><span style="color: #0000ff">null</span><span style="color: #000000">)<br /> {<br /> </span><span style="color: #0000ff">this</span><span style="color: #000000">.TraceValues((System.Collections.Hashtable)Cache[</span><span style="color: #800000">"</span><span style="color: #800000">online</span><span style="color: #800000">"</span><span style="color: #000000">]);<br /> }<br /> }<br /> }<br />}</span></div> |
五.写一个自定义异常类首先要在跟目录下写一个错误显示页面ShowErr.aspx,这个页面根据传递过来的查询字符串msg的值,在一个Label上显示错误信息。
1 |
<div><!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><span style="color: #0000ff">using</span><span style="color: #000000"> System;<br /></span><span style="color: #0000ff">namespace</span><span style="color: #000000"> oa.cls<br />{<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> MyException 的摘要说明。<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">public</span><span style="color: #000000"> </span><span style="color: #0000ff">class</span><span style="color: #000000"> MyException : ApplicationException<br /> {<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 构造函数<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">public</span><span style="color: #000000"> MyException()<br /> : </span><span style="color: #0000ff">base</span><span style="color: #000000">()<br /> {<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 构造函数<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="ErrMessage"></span><span style="color: #008000">异常消息</span><span style="color: #808080"></param></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">public</span><span style="color: #000000"> MyException(</span><span style="color: #0000ff">string</span><span style="color: #000000"> Message)<br /> : </span><span style="color: #0000ff">base</span><span style="color: #000000">(Message)<br /> {<br /> System.Web.HttpContext.Current.Response.Redirect(</span><span style="color: #800000">"</span><span style="color: #800000">~/ShowErr.aspx?msg=</span><span style="color: #800000">"</span><span style="color: #000000"> </span><span style="color: #000000">+</span><span style="color: #000000"> Message);<br /> }<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> 构造函数<br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"></summary></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="Message"></span><span style="color: #008000">异常消息</span><span style="color: #808080"></param></span><span style="color: #008000"><br /> </span><span style="color: #808080">///</span><span style="color: #008000"> </span><span style="color: #808080"><param name="InnerException"></span><span style="color: #008000">引起该异常的异常类</span><span style="color: #808080"></param></span><span style="color: #808080"><br /></span><span style="color: #000000"> </span><span style="color: #0000ff">public</span><span style="color: #000000"> MyException(</span><span style="color: #0000ff">string</span><span style="color: #000000"> Message, Exception InnerException)<br /> : </span><span style="color: #0000ff">base</span><span style="color: #000000">(Message, InnerException)<br /> {<br /> }<br /> }<br />}</span></div> |
转自:http://www.cnblogs.com/hcbin/archive/2010/04/02/1702885.html
View Detailsset msg = server.createobject("jmail.message") msg.logging = true msg.charset = "gb2312" msg.from = "webmaster@w3cnet.com" msg.fromname = "标准网络" msg.addrecipient "w3cnet@qq.com" msg.subject = "会员验证" msg.htmlbody = "<span style=’color:red;'>LED</span>" 'msg.body = "this is html content" msg.addattachment("D:\ximancolor\Jmail\baidu.gif") msg.send("127.0.0.1")
View Details我们在使用C# TextBox进行开发操作的时候经常会碰到C# TextBox的使用,那么C# TextBox的使用有没有一些常用的技巧呢?如C# TextBox换行的处理,其实就是一些常用的操作,那么这里就向你介绍几个我们常见的需求以及解决方法。 一、关于C# TextBox全选的判断: int SelectLength=this.textBox1.SelectionLength;//获取选中的字符长度 if (SelectLength == this.textBox1.Text.Length) {//判断是否全部选中 MessageBox.Show("你已经选中"); } 二、关于C# TextBox换行、设置光标位置、随文本滚动 ◆C# TextBox换行 TextBoxControl.Text += Environment.NewLine; 如何在多行TextBox中写入文本时实现换行?由于Windows系统中,回车符需两上字符。因此方法是使用\r\n标记,如 Label="Calculation " ":…….SUM\r\n"; textBox.AppendText(Label); 另外更有一个办法是用Environment.Newline的方法,能够兼容Windows和Linux系统。 ◆C# TextBox设置光标位置到文本最后 TextBoxControl.SelectionStart = TextBoxControl.TextLength; ◆C# TextBox随文本滚动 TextBoxControl.ScrollToCaret(); 如何在多行TextBox中用滚动条,使添加文本后自动滚动显示到最后一行?方法是使用ScrollToCaret方法,自动滚动到插入符的位置,如: textBox.AppendText(Label); textBox.ScrollToCaret(); 那么对于C# TextBox常用操作的内容就向你介绍到这里,希望对你了解和学习C# TextBox的使用有所帮助。 转自:http://blog.sina.com.cn/s/blog_43eb83b90100l18v.html
View Details一、确保你安装的是最新的补丁 如果门是敞开的话,在窗户上加锁就毫无意义。同样道理,如果你没有打补丁,继续下面的操作就没有什么必要。 二、隐藏Apache的版本号及其它敏感信息 默认情况下,很多Apache安装时会显示版本号及操作系统版本,甚至会显示服务器上安装的是什么样的Apache模块。这些信息可以为黑客所用,并且黑客还可以从中得知你所配置的服务器上的很多设置都是默认状态。 这里有两条语句,你需要添加到你的httpd.conf文件中: ServerSignature Off ServerTokens Prod ServerSignature出现在Apache所产生的像404页面、目录列表等页面的底部。ServerTokens目录被用来判断Apache会在Server HTTP响应包的头部填充什么信息。如果把ServerTokens设为Prod,那么HTTP响应包头就会被设置成: Server:Apache 如果你非常想尝试其它事物,你可以通过编辑源代码改成不是Apache的其它东西,或者你可以通过下面将要介绍的mod_security实现。 三、确保Apache以其自身的用户账号和组运行 有的Apache安装过程使得服务器以nobody的用户运行,所以,假定Apache和你的邮件服务器都是以nobody的账号运行的,那么通过Apache发起的攻击就可能同时攻击到邮件服务器,反之亦然。 User apache Group apache 四、确保web根目录之外的文件没有提供服务 我们不让Apache访问web根目录之外的任何文件。假设你的所以web站点文件都放在一个目录下(例如/web),你可以如下设置: Order Deny,Allow Deny from all Options None AllowOverride None Order Allow,Deny Allow from all 注意,因为我们设置Opitins None 和AllowOverride None,这将关闭服务器的所有Option和Override。你现在必须明确把每个目录设置成Option或者Override。 五、关闭目录浏览 你可以在Directory标签内用Option命令来实现这个功能。设置Option为None或者-Indexes。 Options -Indexes 六、关闭includes 这也可以通过在Directory标签内使用Option命令来实现。设置Option为None或者-Includes。 Options -Includes 七、关闭CGI执行程序 如果你不用CGI,那么请把它关闭。在目录标签中把选项设置成None或-ExecCGI就可以: Options -ExecCGI 八、禁止Apache遵循符号链接 同上,把选项设置成None或-FollowSymLinks: Options -FollowSymLinks 九、关闭多重选项 如果想关闭所有选项,很简单: Options None 如果只想关系一些独立的选项,则通过将Options做如下设置可实现: Options -ExecCGI -FollowSymLinks -Indexes 十、关闭对.htaccess文件的支持 在一个目录标签中实现: AllowOverride None 如果需要重载,则保证这些文件不能够被下载,或者把文件名改成非.htaccess文件。比如,我们可以改成.httpdoverride文件,然后像下面这样阻止所有以.ht打头的文件: AccessFileName .httpdoverride Order allow,deny Deny from all Satisfy All 十一、运行mod_security Run mod_security是O’Reilly出版社出版的Apache Security一书的作者,Ivan Ristic所写的一个非常好用的一个Apache模块。可以用它实现以下功能: ·简单过滤 ·基于过滤的常规表达式 ·URL编码验证 ·Unicode编码验证 ·审计 […]
View DetailsFCKeditor 很强大也很讨人喜欢,唯一的缺点就是不支持文件和文件夹的删除,很是遗憾。这篇文章就介绍怎样为 FCKeditor 增加删除功能(基于 C# 的版本)。 FCKeditor 官方网站:http://www.fckeditor.net本文所针对版本:FCKeditor: 2.6.4,FCKeditor.Net: 2.6.3。 1. 用 Visual Studio 2005/2008 打开项目 FCKeditor.Net 2.6.3,打开文件“FileBrowser/Connector.cs”,为 class Connector 增加如下两个成员函数:
1 |
private void DelFile( XmlNode connectorNode, string resourceType, string currentFolder ) { HttpContext hc = HttpContext.Current; string file = hc.Server.MapPath(hc.Request["FileUrl"]); if (System.IO.File.Exists(file)) System.IO.File.Delete(file); else hc.Response.Write(@"<error number=""1"" originaldescription=""unable to locate file"">"); } private void DelFolder( XmlNode connectorNode, string resourceType, string currentFolder ) { HttpContext hc = HttpContext.Current; string folder = hc.Server.MapPath(hc.Request["FolderName"]); if (System.IO.Directory.Exists(folder)) System.IO.Directory.Delete(folder, true); else hc.Response.Write(@"<error number=""2"" originaldescription=""unable to locate folder"">"); } |
2. 在文件“Connector.cs”中找到 OnLoad 函数,在 switch 部分增加以下红色代码:
1 |
// Execute the required command. switch( sCommand ) { case "GetFolders" : this.GetFolders( oConnectorNode, sResourceType, sCurrentFolder ); break; case "GetFoldersAndFiles" : this.GetFolders( oConnectorNode, sResourceType, sCurrentFolder ); this.GetFiles( oConnectorNode, sResourceType, sCurrentFolder ); break; case "CreateFolder": this.CreateFolder(oConnectorNode, sResourceType, sCurrentFolder); break; <span><font color="#ff0000" face="Courier New">case "DelFile": this.DelFile(oConnectorNode, sResourceType, sCurrentFolder); break; case "DelFolder": this.DelFolder(oConnectorNode, sResourceType, sCurrentFolder); break;</font></span> } |
3. 编译 FCKeditor.net 并关闭该项目。将生成的 FredCK.FCKeditorV2.dll 拷贝出来以备后用。 4. 建立 C# 测试项目,并在其中部署 FCKeditor 2.6.4(使用第 3 步生成的 FredCK.FCKeditorV2.dll)。精简及部署的详细步骤非本文重点,不再重复。 5. 打开“fckeditor/editor/filemanager/browser/default/frmresourceslist.htm”,修改以下两个函数
1 |
oListManager.GetFolderRowHtml = function( folderName, folderPath<font face="Courier New"><span><font color="#ff0000">, folderUrl</font></span> ) { // Build the link to view the folder. var sLink = '<a href="#" onclick="OpenFolder(\'' + ProtectPath(folderPath) + '\');return false;">'; return '<tr>' + '<td width="16">' + sLink + '<img alt="" src="images/Folder.gif" width="16" height="16" border="0"><\/a>' + '<\/td><td nowrap colspan="2"> ' + sLink + folderName + '<\/a>' + '<\/td><span><font color="#ff0000"><td align="right"><a href="#" onclick="DelFolder(\''+folderName+'\',\''+ ProtectPath(folderUrl) + '\');return false;">删除</a></td<span><font color="#ff0000">></font></span><</font></span>\/tr>'; } oListManager.GetFileRowHtml = function( fileName, fileUrl, fileSize ) { // Build the link to view the folder. var sLink = '<a href="#" onclick="OpenFile(\'' + ProtectPath(fileUrl) + '\');return false;">' ; // Get the file icon. va sIcon = oIcons.GetIcon( fileName ) <span><font color="#ff0000"><td align="right"><a href="#" onclick="DelFile(\''+fileName+'\',\'' + ProtectPath(fileUrl) + '\');return false;">删除</a></td></font></span></font><\/tr>'; } |
6. 继续修改文件“frmresourceslist.htm”,在 OpenFile 函数后面增加以下两个函数:
1 |
function DelFile( fileName, fileUrl ) { if (confirm('您确定要删除文件“' + fileName + '”吗?')) oConnector.SendCommand("DelFile", "FileUrl=" + escape(fileUrl), Refresh); } function DelFolder( folderName, folderPath ) { if (confirm('您确定要删除文件夹“' + folderName + '”和里面的所有文件吗?')) oConnector.SendCommand("DelFolder", "FolderName=" + escape(folderPath + folderName), Refresh); } |
7. 继续修改文件“frmresourceslist.htm”,找到 GetFoldersAndFilesCallBack 函数中的下面这行,增加红色部分的代码:
1 |
oHtml.Append( oListManager.GetFolderRowHtml( sFolderName, sCurrentFolderPath + sFolderName + "/"<span><font color="#ff0000" face="Courier New">, <span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New"><span><font color="#ff0000" face="Courier New">sCurrentFolderUrl</font></span> </font></span></font></span></font></span></font></span></font></span></font></span></font></span></font></span>) ); |
至此,删除功能增加完毕,见下图: 转自:http://blog.sina.com.cn/s/blog_4dfeeb6f0100ed5j.html
View Details大家好,这是我最近写了一个Udp通信的小程序,发表出来和大家共同学习,我希望和大家共同进步。 upd通信接受端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
using System; using System.Net; using System.Net.Sockets; namespace Zhty.Socket.UDPSocket { public class UDP_Client { #region 属性 private IPAddress _ClientAddress = IPAddress.Any; private int _ClientPort = 0; private byte[] _data = new byte[] { }; public IPEndPoint Client { get { return new IPEndPoint(_ClientAddress, _ClientPort); } set { _ClientAddress = value.Address; _ClientPort = value.Port; } } public IPAddress ClientAddress { get { return _ClientAddress; } set { _ClientAddress = value; } } public int ClientPort { get { return _ClientPort; } set { _ClientPort = value; } } #endregion #region 方法 public void SendMessage(byte[] message) { // Encode message per settings // Send the message _data = message; try { SendUDPMessage(_data); } catch (Exception ex) { throw ex; } } private int SendUDPMessage(Byte[] _data) { //' Create a UDP Server and send the message, then clean up UdpClient _UDPServer = null; int ReturnCode; try { _UDPServer = new UdpClient(); ReturnCode = 0; _UDPServer.Connect(Client); ReturnCode = _UDPServer.Send(_data, _data.Length); } catch (Exception ex) { throw ex; } finally { if (_UDPServer != null) { _UDPServer.Close(); } } return ReturnCode; } #endregion } } |
udp通信的发送端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Net.Sockets; using System.Net; namespace Zhty.Socket.UDPSocket { public class UDP_Server { private Thread _ThreadReceive; private int _ClientPort = 0; private string _Message = null; private UdpClient _UDPClient; private IPEndPoint _Server = new IPEndPoint(IPAddress.Any, 0); private int _BytesReceived = 0; #region 事件定义 public delegate void OnReceivedDataHandler(object sender, DataReceivedEventArgs e); public event OnReceivedDataHandler OnRecivedData; public delegate void OnStateChangedHandler(object sender, ServerStateChangeEventArgs e); public event OnStateChangedHandler OnStateChanged; #endregion #region 属性 int _bufferSize = 1024; public int BufferSize { get { return _bufferSize; } set { _bufferSize = value; } } public int BytesReceived { get { return _BytesReceived; } } public string Message { get { return _Message; } } public int ClientPort { get { return _ClientPort; } set { _ClientPort = value; } } #endregion #region 方法 void DataReceiveProc() { //BeforeReceive(this,new EventArgs()); _Message = ""; byte[] data = new byte[BufferSize]; try { data = _UDPClient.Receive(ref _Server); if (OnRecivedData != null) OnRecivedData(this, new DataReceivedEventArgs(data)); Thread.Sleep(100); } catch (Exception ex) { if (OnStateChanged != null) OnStateChanged(this, new ServerStateChangeEventArgs(false)); throw ex; } finally { InitializeThread(); } } private void InitializeClient() { if (_UDPClient == null) { this._UDPClient = new UdpClient(ClientPort); } } private void InitializeThread() { try { _ThreadReceive = new Thread(new ThreadStart(DataReceiveProc)); _ThreadReceive.Start(); } catch (Exception ex) { throw ex; } } public void Start() { InitializeClient(); InitializeThread(); } #endregion public void Stop() { try { _ThreadReceive.Abort(); if (_UDPClient != null) { // ' Close the UDPClient and then force it to Nothing _UDPClient.Close(); _UDPClient = null; } } catch (Exception ex) { throw ex; } } #region 析构方法 ~UDP_Server() { Stop(); } #endregion } } |
辅助类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
using System; using System.Collections.Generic; using System.Text; namespace Zhty.Socket.UDPSocket { public class DataReceivedEventArgs : EventArgs { public DataReceivedEventArgs(byte[] data) { Data = data; } byte[] m_Data; public byte[] Data { get { return m_Data; } set { m_Data = value; } } } public class ServerStateChangeEventArgs : EventArgs { public ServerStateChangeEventArgs(bool state) { Running = state; } bool m_Running; public bool Running { get { return m_Running; } set { m_Running = value; } } } } |
转自:http://www.cnblogs.com/zhaotianyu001/articles/549259.html
View DetailsInternet协议族中有支持无连接的传输协议,即UDP协议。UDP协议提供了一种方法来发送经过封装的IP数据报,而且不必建立连接就 可以发送这些IP数据报。 服务器端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace UDPServer { class Program { static void Main(string[] args) { int recv; byte[] data = new byte[1024]; //构建TCP 服务器 //得到本机IP,设置TCP端口号 IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 8001); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //绑定网络地址 newsock.Bind(ipep); Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName()); //等待客户机连接 Console.WriteLine("Waiting for a client"); //得到客户机IP IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)(sender); recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}: ", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); //客户机连接成功后,发送欢迎信息 string welcome = "Welcome ! "; //字符串与字节数组相互转换 data = Encoding.ASCII.GetBytes(welcome); //发送信息 newsock.SendTo(data, data.Length, SocketFlags.None, Remote); while (true) { data = new byte[1024]; //发送接受信息 recv = newsock.ReceiveFrom(data, ref Remote); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); newsock.SendTo(data, recv, SocketFlags.None, Remote); } } } } |
客户端:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace UDPClient { class Program { static void Main(string[] args) { byte[] data = new byte[1024]; string input, stringData; //构建TCP 服务器 Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName()); //设置服务IP,设置TCP端口号 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001); //定义网络类型,数据连接类型和网络协议UDP Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); string welcome = "Hello! "; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, ipep); IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint Remote = (EndPoint)sender; data = new byte[1024]; //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制 //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100); int recv = server.ReceiveFrom(data, ref Remote); Console.WriteLine("Message received from {0}: ", Remote.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); while (true) { input = Console.ReadLine(); if (input == "exit") break; server.SendTo(Encoding.ASCII.GetBytes(input), Remote); data = new byte[1024]; recv = server.ReceiveFrom(data, ref Remote); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Stopping Client."); server.Close(); } } } |
MSDN 实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// This constructor arbitrarily assigns the local port number. UdpClient udpClient = new UdpClient(11000); try{ udpClient.Connect("www.contoso.com ", 11000); // Sends a message to the host to which you have connected. Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?"); udpClient.Send(sendBytes, sendBytes.Length); // Sends a message to a different host using optional hostname and port parameters. UdpClient udpClientB = new UdpClient(); udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000); //IPEndPoint object will allow us to read datagrams sent from any source. IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // Blocks until a message returns on this socket from a remote host. Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); // Uses the IPEndPoint object to determine which of these two hosts responded. Console.WriteLine("This is the message you received " + returnData.ToString()); Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString()); udpClient.Close(); udpClientB.Close(); } catch (Exception e ) { Console.WriteLine(e.ToString()); } |
Microsoft Visual Studio 2005/.NET Framework 2.0 同时提供下列产品的其他版本: •.NET Framework 3.0 •Microsoft Visual Studio 2008/.NET Framework 3.5 .NET Framework 类库UdpClient 成员 提供用户数据报 (UDP) 网络服务。 下表列出了由 UdpClient 类型公开的成员。 公共构造函数 名称 说明 UdpClient 已重载。初始化 UdpClient 类的新实例。 公共属性 (请参见 受保护的属性 ) 名称 说明 Available 获取从网络接收的可读取的数据量。 Client 获取或设置基础网络 Socket。 DontFragment 获取或设置 Boolean 值,指定 UdpClient 是否允许对 Internet 协议 (IP) 数据报进行分段。 EnableBroadcast 获取或设置 Boolean 值,指定 UdpClient 是否可以发送或接收广播数据包。 ExclusiveAddressUse 获取或设置 Boolean 值,指定 UdpClient 是否只允许一个客户端使用端口。 MulticastLoopback 获取或设置 Boolean 值,指定是否将输出多路广播数据包传递给发送应用程序。 Ttl 获取或设置一个值,指定由 UdpClient 发送的 Internet […]
View Detailsaddcslashes —— 为字符串里面的部分字符添加反斜线转义字符 addslashes —— 用指定的方式对字符串里面的字符进行转义 bin2hex —— 将二进制数据转换成十六进制表示 chr —— 返回一个字符的ASCII码 chunk_split —— 按一定的字符长度将字符串分割成小块 convert_cyr_string —— 将斯拉夫语字符转换为别的字符 convert_uudecode —— 解密一个字符串 convert_uuencode —— 加密一个字符串 count_chars —— 返回一个字符串里面的字符使用信息 crc32 —— 计算一个字符串的crc32多项式 crypt —— 单向散列加密函数 explode —— 将一个字符串用分割符转变为一数组形式 fprintf —— 按照要求对数据进行返回,并直接写入文档流 get_html_translation_table —— 返回可以转换的HTML实体 html_entity_decode —— htmlentities ()函数的反函数,将HTML实体转换为字符 htmlentities —— 将字符串中一些字符转换为HTML实体 htmlspecialchars_decode —— htmlspecialchars()函数的反函数,将HTML实体转换为字符 htmlspecialchars —— 将字符串中一些字符转换为HTML实体 implode —— 将数组用特定的分割符转变为字符串 join —— 将数组转变为字符串,implode()函数的别名 levenshtein —— 计算两个词的差别大小 localeconv —— 获取数字相关的格式定义 ltrim —— 去除字符串左侧的空白或者指定的字符 md5_file —— 将一个文件进行MD5算法加密 md5 —— 将一个字符串进行MD5算法加密 metaphone —— 判断一个字符串的发音规则 money_format —— 按照参数对数字进行格式化的输出 nl_langinfo —— 查询语言和本地信息 nl2br —— 将字符串中的换行符“\n”替换成“” […]
View Details