博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件
阅读量:6457 次
发布时间:2019-06-23

本文共 6330 字,大约阅读时间需要 21 分钟。

服务端:

 

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>

 

转载地址:http://pgnzo.baihongyu.com/

你可能感兴趣的文章
Android内存泄露之开篇
查看>>
leetcode-38 Count And Say
查看>>
提高效率—编程中的技巧
查看>>
导出excel——弹出框
查看>>
高并发程序设计
查看>>
ExtJs之组件(window)
查看>>
SoapUI中如何传递cookie
查看>>
shell中的一些技巧和知识
查看>>
eclipse 导出Runnable JAR file ,双击无法执行原因与解决 双击后闪退的原因 批处理java打包文件 @echo off start javaw -jar *.jar...
查看>>
静态成员变量的初始化
查看>>
POJ 1269 Intersecting Lines(判断两直线位置关系)
查看>>
MSSQL数据库跨表和跨数据库查询方法简(转)
查看>>
spring3.0.7中各个jar包的作用总结
查看>>
Windows 10 /win10 上使用GIT慢的问题,或者命令行反应慢的问题
查看>>
SSM——查询_分页
查看>>
梯度下降(Gradient descent)
查看>>
Windows平台分布式架构实践 - 负载均衡
查看>>
如何让LinearLayout也有类似Button的点击效果?
查看>>
JAVA读取文件方法大全
查看>>
寻找最小的k个数
查看>>