用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) !=  1return;
             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( 020),  " 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,如需转载请自行联系原作者
相关文章
|
1月前
|
存储 弹性计算 数据可视化
要将ECS中的文件直接传输到阿里云网盘与相册(
【2月更文挑战第31天】要将ECS中的文件直接传输到阿里云网盘与相册(
420 4
|
1月前
|
存储 资源调度 应用服务中间件
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
浅谈本地开发好的 Web 应用部署到 ABAP 应用服务器上的几种方式
27 0
|
25天前
|
域名解析 网络协议 Linux
使用 Webmin+bind9快速搭建私有DNS服务器
使用 Webmin+bind9快速搭建私有DNS服务器
68 1
|
1月前
|
机器学习/深度学习 算法 编译器
【C++ 泛型编程 中级篇】深度解析C++:类型模板参数与非类型模板参数
【C++ 泛型编程 中级篇】深度解析C++:类型模板参数与非类型模板参数
47 0
|
1月前
|
缓存 前端开发 Java
【二十八】springboot之通过threadLocal+参数解析器实现同session一样保存当前登录信息的功能
【二十八】springboot之通过threadLocal+参数解析器实现同session一样保存当前登录信息的功能
34 1
|
1月前
|
Linux 网络安全 Python
如何在服务器上运行python文件
如何在服务器上运行python文件
|
1月前
|
域名解析 存储 网络协议
Linux中搭建主从DNS服务器
搭建主从DNS架构以提升DNS服务的高可用性、负载均衡和数据冗余。主服务器配置涉及编辑`/etc/named.conf`,设置监听IP和允许查询的范围,并定义主区域及允许的数据传输。从服务器配置需指定为奴隶类型,并指明主服务器的IP。测试表明正反向查询解析均正常。注意配置文件的语法正确性和权限设置。
|
4天前
|
前端开发 Java
SpringBoot之实体参数的详细解析
SpringBoot之实体参数的详细解析
10 0
|
21天前
|
监控 负载均衡 网络协议
DNS服务器的搭建之初体验
通过这些步骤,你可以在初次搭建DNS服务器时获得基本的体验,了解如何为域名提供解析服务,促进网络的正常运行。 买CN2云服务器,免备案服务器,高防服务器,就选蓝易云。百度搜索:蓝易云
38 7
|
28天前
|
网络协议 Linux 网络安全
Linux服务器DNS服务器配置实现bind的正向解释和反向解释
Linux服务器DNS服务器配置实现bind的正向解释和反向解释
17 0

推荐镜像

更多