用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件
生活随笔
收集整理的這篇文章主要介紹了
用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
服務端:
?
public?class?AdvertisementSource?:?IDisposable????{
????????HttpListener?httpListener;
????????bool?stopped;
????????#region?構造和析構
????????//==
????????#region?IDisposable
????????[System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
????????int?disposedFlag;
????????~AdvertisementSource()
????????{
????????????Dispose(false);
????????}
????????///?<summary>
????????///?釋放所占用的資源
????????///?</summary>
????????public?void?Dispose()
????????{
????????????Dispose(true);
????????????GC.SuppressFinalize(this);
????????}
????????///?<summary>
????????///?獲取該對象是否已經被釋放
????????///?</summary>
????????[System.ComponentModel.Browsable(false)]
????????public?bool?IsDisposed
????????{
????????????get
????????????{
????????????????return?disposedFlag?!=?0;
????????????}
????????}
????????#endregion
????????protected?virtual?void?Dispose(bool?disposing)
????????{
????????????if?(System.Threading.Interlocked.Increment(ref?disposedFlag)?!=?1)?return;
????????????if?(disposing)
????????????{
????????????????httpListener.Stop();
????????????}
????????????//在這里編寫非托管資源釋放代碼
????????}
????????#endregion
????????public?void?Initialize()
????????{
????????????httpListener?=?new?HttpListener();
????????????httpListener.Prefixes.Add(string.Format("http://*:{0}/AdSource/",?8080));
????????????httpListener.Start();
????????????httpListener.BeginGetContext(GetHttpContextCallback,?null);
????????}???????
????????
????????public?void?GetHttpContextCallback(IAsyncResult?iar)
????????{
????????????if?(stopped)?return;
????????????var?context?=?httpListener.EndGetContext(iar);
????????????httpListener.BeginGetContext(GetHttpContextCallback,?null);
????????????string?endPoint?=?context.Request.RemoteEndPoint.ToString();
????????????int?spIndex?=?endPoint.IndexOf(":");
????????????endPoint?=?endPoint.Substring(0,?spIndex);
???????????
????????????using?(HttpListenerResponse?response?=?context.Response)
????????????{ //get?的方式在如下解析即可得到客戶端參數及值
????????????????//string?userName?=?context.Request.QueryString["userName"];
????????????????//string?password?=?context.Request.QueryString["password"];
????????????????//string?suffix?=?context.Request.QueryString["suffix"];
????????????????//string?adType?=?context.Request.QueryString["adtype"];//文字,圖片,視頻
?????????????
????????????????
????????????????if?(!context.Request.HasEntityBody)//無數據
????????????????{
????????????????????response.StatusCode?=?403;
????????????????????return;
????????????????}
????????????????string?userName?=?"";
????????????????string?password?=?"";
????????????????string?suffix?=?"";
????????????????string?adType?=?"";
???????????????//post?的方式有文件上傳的在如下解析即可得到客戶端參數及值
????????????????HttpListenerRequest?request?=?context.Request;????????????????
????????????????if?(request.ContentType.Length?>?20?&&?string.Compare(request.ContentType.Substring(0,?20),?"multipart/form-data;",?true)?==?0)
????????????????{
????????????????????List<Values>?lst?=?new?List<Values>();
????????????????????Encoding?Encoding?=?request.ContentEncoding;
????????????????????string[]?values?=?request.ContentType.Split(';').Skip(1).ToArray();
????????????????????string?boundary?=?string.Join(";",?values).Replace("boundary=",?"").Trim();
????????????????????byte[]?ChunkBoundary?=?Encoding.GetBytes("--"?+?boundary?+?"\r\n");
????????????????????byte[]?EndBoundary?=?Encoding.GetBytes("--"?+?boundary?+?"--\r\n");
????????????????????Stream?SourceStream?=?request.InputStream;
????????????????????var?resultStream?=?new?MemoryStream();
????????????????????bool?CanMoveNext?=?true;
????????????????????Values?data?=?null;
????????????????????while?(CanMoveNext)
????????????????????{
????????????????????????byte[]?currentChunk?=?ReadLineAsBytes(SourceStream);
????????????????????????if?(!Encoding.GetString(currentChunk).Equals("\r\n"))
????????????????????????????resultStream.Write(currentChunk,?0,?currentChunk.Length);
????????????????????????if?(CompareBytes(ChunkBoundary,?currentChunk))
????????????????????????{
????????????????????????????byte[]?result?=?new?byte[resultStream.Length?-?ChunkBoundary.Length];
????????????????????????????resultStream.Position?=?0;
????????????????????????????resultStream.Read(result,?0,?result.Length);
????????????????????????????CanMoveNext?=?true;
????????????????????????????if?(result.Length?>?0)
????????????????????????????????data.datas?=?result;
????????????????????????????data?=?new?Values();
????????????????????????????lst.Add(data);
????????????????????????????resultStream.Dispose();
????????????????????????????resultStream?=?new?MemoryStream();
????????????????????????}
????????????????????????else?if?(Encoding.GetString(currentChunk).Contains("Content-Disposition"))
????????????????????????{
????????????????????????????byte[]?result?=?new?byte[resultStream.Length?-?2];
????????????????????????????resultStream.Position?=?0;
????????????????????????????resultStream.Read(result,?0,?result.Length);
????????????????????????????CanMoveNext?=?true;
????????????????????????????data.name?=?Encoding.GetString(result).Replace("Content-Disposition:?form-data;?name=\"",?"").Replace("\"",?"").Split(';')[0];
????????????????????????????resultStream.Dispose();
????????????????????????????resultStream?=?new?MemoryStream();
????????????????????????}
????????????????????????else?if?(Encoding.GetString(currentChunk).Contains("Content-Type"))
????????????????????????{
????????????????????????????CanMoveNext?=?true;
????????????????????????????data.type?=?1;
????????????????????????????resultStream.Dispose();
????????????????????????????resultStream?=?new?MemoryStream();
????????????????????????}
????????????????????????else?if?(CompareBytes(EndBoundary,?currentChunk))
????????????????????????{
????????????????????????????byte[]?result?=?new?byte[resultStream.Length?-?EndBoundary.Length?-?2];
????????????????????????????resultStream.Position?=?0;
????????????????????????????resultStream.Read(result,?0,?result.Length);
????????????????????????????data.datas?=?result;
????????????????????????????resultStream.Dispose();
????????????????????????????CanMoveNext?=?false;
????????????????????????}
????????????????????}
????????????????????foreach?(var?key?in?lst)
????????????????????{
????????????????????????if?(key.type?==?0)
????????????????????????{
????????????????????????????string?value?=?Encoding.GetString(key.datas).Replace("\r\n",?"");
????????????????????????????if?(key.name?==?"username")
????????????????????????????????userName?=?value;
????????????????????????????if?(key.name?==?"password")
????????????????????????????????password?=?value;
????????????????????????????if?(key.name?==?"suffix")
????????????????????????????????suffix?=?value;
????????????????????????????if?(key.name?==?"adtype")
????????????????????????????????adType?=?value;
????????????????????????}????????????????????????
????????????????????????if?(key.type?==?1)
????????????????????????{
????????????????????????????FileStream?fs?=?new?FileStream("c:\\3.jpg",?FileMode.Create);
????????????????????????????fs.Write(key.datas,?0,?key.datas.Length);
????????????????????????????fs.Close();
????????????????????????????fs.Dispose();
????????????????????????}
????????????????????}
???????????????????
????????????????????if?(userName?!=?"test"?||?password?!=?"test"?||?string.IsNullOrEmpty(suffix)?||?string.IsNullOrEmpty(adType))
????????????????????{
????????????????????????response.StatusCode?=?403;
????????????????????????return;
????????????????????}
????????????????????int?adtype?=?0;
????????????????????int.TryParse(adType,?out?adtype);
????????????????}
????????????????response.ContentType?=?"text/html;charset=utf-8";
????????????????try
????????????????{
????????????????????using?(System.IO.Stream?output?=?response.OutputStream)
????????????????????using?(StreamWriter?writer?=?new?StreamWriter(output,?Encoding.UTF8))
????????????????????????writer.WriteLine("接收完成!");
????????????????}
????????????????catch
????????????????{
????????????????}
????????????????response.Close();
????????????}
????????}
????????byte[]?ReadLineAsBytes(Stream?SourceStream)
????????{
????????????var?resultStream?=?new?MemoryStream();
????????????while?(true)
????????????{
????????????????int?data?=?SourceStream.ReadByte();
????????????????resultStream.WriteByte((byte)data);
????????????????if?(data?==?10)
????????????????????break;
????????????}
????????????resultStream.Position?=?0;
????????????byte[]?dataBytes?=?new?byte[resultStream.Length];
????????????resultStream.Read(dataBytes,?0,?dataBytes.Length);
????????????return?dataBytes;
????????}
?????????
????????bool?CompareBytes(byte[]?source,?byte[]?comparison)
????????{
????????????int?count?=?source.Length;
????????????if?(source.Length?!=?comparison.Length)
????????????????return?false;
????????????for?(int?i?=?0;?i?<?count;?i++)
????????????????if?(source[i]?!=?comparison[i])
????????????????????return?false;
????????????return?true;
????????}
????????public?class?Values
????????{
????????????public?int?type?=?0;//0參數,1文件
????????????public?string?name;
????????????public?byte[]?datas;
????????}
????}
客戶端:
?
<!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>
????<title></title>???
</head>
<body>
????<form?method="post"?enctype="multipart/form-data"?action="http://127.0.0.1:8080/AdSource/">
????<p>
????????<input?id="File1"?name="file1"?type="file"?/></p>
??<p>
????????<input?id="username"?name="username"?type="text"?value="test"?/></p>
??????<p>
????????<input?id="password"?name="password"?type="text"?value="test"?/></p>
????<p>
????????<input?id="suffix"?name="suffix"?type="text"?value="txt"?/></p>
????<p>
????????<input?id="adtype"?name="adtype"?type="text"?value="0"/></p>
????<p>
????????<input?id="Button1"?type="submit"?value="submit"??/></p>
????</form>????
</body>
</html>
本文轉自94cool博客園博客,原文鏈接:http://www.cnblogs.com/94cool/archive/2011/10/25/2223457.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在centos6中安装2.4版本的HTT
- 下一篇: zabbix配置邮箱报警