废话不多讲,由于种种原因项目上出现了移动手持录入标签信息通过pc端转接实现打印的需求,所以简单研究了一下,本来考虑使用webapi方式实现,但是发现这种方式调用打印机实现自动打印比较困难,所以转而求其次就用了他:winform程序实现HttpListener对地址的监听。上正餐:

1. 项目结构:类HttpPostListener(实现监听业务类),HttpListenerPostValue(监听工具类)

2.HttpPostListener 代码

   public class HttpPostListener
{
private static HttpListener httpPostRequest = new HttpListener(); public static void BizLister(string[] url)
{
foreach (var itm in url)
{
httpPostRequest.Prefixes.Add(itm);
BizReStatus.MonitorLinks.Add(itm,new MonitorLinkInfo() { AddrLink = itm, LastRequstTime = DateTime.Now }); ShowFormData.Instance.ShowFormInfo(new ShowInfoData("添加监控:"+itm, ShowInfoType.logInfo));
}
httpPostRequest.Start(); ShowFormData.Instance.ShowFormInfo(new ShowInfoData("添加监控初始化添加完成,正在启动监控。。。", ShowInfoType.logInfo)); ShowFormData.Instance.ShowFormInfo(new ShowInfoData("刷新监控列表", ShowInfoType.MonitorLink)); Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));
ThrednHttpPostRequest.Start();
ThrednHttpPostRequest.IsBackground = true;
ShowFormData.Instance.ShowFormInfo(new ShowInfoData("后台监控已启动,正在监控请求。。。", ShowInfoType.logInfo));
} private static void httpPostRequestHandle()
{
while (true)
{
try
{
HttpListenerContext requestContext = httpPostRequest.GetContext();
Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>
{
try
{ var rMsg = "请求成功";
PalletLableInfo lableInfor = new PalletLableInfo();
HttpListenerContext request = (HttpListenerContext)requestcontext; ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"接收到请求【{request.Request.RemoteEndPoint.Address}】,正在处理。。。", ShowInfoType.logInfo));
//获取Post请求中的参数和值帮助类
HttpPostListenerHelper httppost = new HttpPostListenerHelper(request); if (request.Request.Headers.AllKeys.Contains("Origin") && request.Request.HttpMethod == "OPTIONS")
{
                   //此处解决移动端js请求跨域的问题
request.Response.StatusCode = ;
request.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
request.Response.Headers.Add("Access-Control-Allow-Methods", " POST, OPTIONS");
request.Response.ContentType = "application/json";
requestContext.Response.ContentEncoding = Encoding.UTF8; using (StreamWriter writer = new StreamWriter(request.Response.OutputStream))
{
writer.Write("");
writer.Close();
request.Response.Close();
}
return;
} if (request.Request.ContentType != null)
{
                    //application/json等类型的请求处理,Json格式参数
if (request.Request.ContentType == "application/json" || request.Request.ContentType == "text/plain" || request.Request.ContentType == "application/xml" || request.Request.ContentType == "text/xml")
{
//获取Post过来的参数和数据
lableInfor = httppost.GetPalletLableInfoValue();
if (lableInfor.isPrint == )
{
foreach (var item in lableInfor.data)
{
lableInfor.htm = lableInfor.htm.Replace("data-" + item.Key.ToLower() + "=\"1\"", "value=\"" + item.Value + "\"");
}
BizReStatus.MonitorLinks[request.Request.Url.OriginalString].PalletLableInfo.Add(Guid.NewGuid().ToString(), lableInfor); BizReStatus.MonitorLinks[request.Request.Url.OriginalString].CurrPalletLableInfo = lableInfor;
ShowFormData.Instance.ShowFormInfo(new ShowInfoData(lableInfor, ShowInfoType.PalletLable));
ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"请求【{1}】,处理完成,正在准备打印。。。", ShowInfoType.logInfo));
ShowFormData.Instance.ShowFormInfo(new ShowInfoData("刷新监控列表", ShowInfoType.MonitorLink));
}
else
{
rMsg = "请求成功,但未获取到有效数据。";
ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"请求【{1}】,处理完成,未获取到有效数据。", ShowInfoType.logInfo));
}
}
                    //form表单类型请求处理
else if (request.Request.ContentType.Length > && string.Compare(request.Request.ContentType.Substring(, ), "multipart/form-data;", true) == )
{
//获取Post过来的参数和数据
List<HttpListenerPostValue> lst = httppost.GetHttpListenerPostValue();
//使用方法
foreach (var key in lst)
{
if (key.type == )
{
string value = Encoding.UTF8.GetString(key.datas).Replace("\r\n", "");
if (key.name == "isprint")
{
lableInfor.isPrint = Convert.ToInt32(value);
Console.WriteLine(value);
}
if (key.name == "htm")
{
lableInfor.htm = value;
Console.WriteLine(value);
}
if (key.name == "username")
{
//suffix = value;
Console.WriteLine(value);
}
}
if (key.type == )
{
string fileName = request.Request.QueryString["FileName"];
if (!string.IsNullOrEmpty(fileName))
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyMMdd_HHmmss_ffff") + Path.GetExtension(fileName).ToLower();
if (key.name == "File")
{
FileStream fs = new FileStream(filePath, FileMode.Create);
fs.Write(key.datas, , key.datas.Length);
fs.Close();
fs.Dispose();
}
}
}
} if (lableInfor.isPrint == )
{
BizReStatus.MonitorLinks[request.Request.Url.OriginalString].PalletLableInfo.Add(Guid.NewGuid().ToString(), lableInfor); ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"请求【{1}】,处理完成,正在准备打印。。。", ShowInfoType.logInfo));
ShowFormData.Instance.ShowFormInfo(new ShowInfoData("刷新监控列表", ShowInfoType.MonitorLink));
}
else
{
rMsg = "请求成功,但未获取到有效数据。";
ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"请求【{1}】,处理完成,未获取到有效数据。", ShowInfoType.logInfo));
}
}
else
{
rMsg = "请求失败:未识别请求类型";
}
} //Response
request.Response.StatusCode = ;
request.Response.Headers.Add("Access-Control-Allow-Origin", "*");
request.Response.ContentType = "application/json";
requestContext.Response.ContentEncoding = Encoding.UTF8;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(new { success = "true", msg = rMsg }));
request.Response.ContentLength64 = buffer.Length;
var output = request.Response.OutputStream;
output.Write(buffer, , buffer.Length);
output.Close(); ShowFormData.Instance.ShowFormInfo(new ShowInfoData($"请求【{1}】,处理结束,已反馈。", ShowInfoType.logInfo));
}
catch (Exception ex)
{
} }));
threadsub.Start(requestContext);
}
catch (Exception ex)
{ }
} }
}

3.HttpListenerPostValue(监听工具类)代码

  /// <summary>
/// HttpListenner监听Post请求参数值实体
/// </summary>
public class HttpListenerPostValue
{
/// <summary>
/// 0=> 参数
/// 1=> 文件
/// </summary>
public int type = ;
public string name;
public byte[] datas;
} /// <summary>
/// 获取Post请求中的参数和值帮助类
/// </summary>
public class HttpPostListenerHelper
{
private HttpListenerContext request; public HttpPostListenerHelper(HttpListenerContext request)
{
this.request = request;
} private bool CompareBytes(byte[] source, byte[] comparison)
{
try
{
int count = source.Length;
if (source.Length != comparison.Length)
return false;
for (int i = ; i < count; i++)
if (source[i] != comparison[i])
return false;
return true;
}
catch
{
return false;
}
} private byte[] ReadFullAsBytes(Stream SourceStream)
{
var resultStream = new MemoryStream();
while (true)
{
int data = SourceStream.ReadByte();
if (data < )
break; resultStream.WriteByte((byte)data);
//if (data == 10)
// break; }
resultStream.Position = ;
byte[] dataBytes = new byte[resultStream.Length];
resultStream.Read(dataBytes, , dataBytes.Length);
return dataBytes;
} private byte[] ReadLineAsBytes(Stream SourceStream)
{
var resultStream = new MemoryStream();
while (true)
{
int data = SourceStream.ReadByte();
resultStream.WriteByte((byte)data);
if (data == )
break;
}
resultStream.Position = ;
byte[] dataBytes = new byte[resultStream.Length];
resultStream.Read(dataBytes, , dataBytes.Length);
return dataBytes;
} /// <summary>
/// 获取Post过来的参数和数据
/// </summary>
/// <returns></returns>
public List<HttpListenerPostValue> GetHttpListenerPostValue()
{
try
{
List<HttpListenerPostValue> HttpListenerPostValueList = new List<HttpListenerPostValue>();
if (request.Request.ContentType.Length > && string.Compare(request.Request.ContentType.Substring(, ), "multipart/form-data;", true) == )
{
string[] HttpListenerPostValue = request.Request.ContentType.Split(';').Skip().ToArray();
string boundary = string.Join(";", HttpListenerPostValue).Replace("boundary=", "").Trim();
byte[] ChunkBoundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
byte[] EndBoundary = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
Stream SourceStream = request.Request.InputStream;
var resultStream = new MemoryStream();
bool CanMoveNext = true;
HttpListenerPostValue data = null;
while (CanMoveNext)
{
byte[] currentChunk = ReadLineAsBytes(SourceStream);
if (!Encoding.UTF8.GetString(currentChunk).Equals("\r\n"))
resultStream.Write(currentChunk, , currentChunk.Length);
if (CompareBytes(ChunkBoundary, currentChunk))
{
byte[] result = new byte[resultStream.Length - ChunkBoundary.Length];
resultStream.Position = ;
resultStream.Read(result, , result.Length);
CanMoveNext = true;
if (result.Length > )
data.datas = result;
data = new HttpListenerPostValue();
HttpListenerPostValueList.Add(data);
resultStream.Dispose();
resultStream = new MemoryStream(); }
else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Disposition"))
{
byte[] result = new byte[resultStream.Length - ];
resultStream.Position = ;
resultStream.Read(result, , result.Length);
CanMoveNext = true;
data.name = Encoding.UTF8.GetString(result).Replace("Content-Disposition: form-data; name=\"", "").Replace("\"", "").Split(';')[];
resultStream.Dispose();
resultStream = new MemoryStream();
}
else if (Encoding.UTF8.GetString(currentChunk).Contains("Content-Type"))
{
CanMoveNext = true;
data.type = ;
resultStream.Dispose();
resultStream = new MemoryStream();
}
else if (CompareBytes(EndBoundary, currentChunk))
{
byte[] result = new byte[resultStream.Length - EndBoundary.Length - ];
resultStream.Position = ;
resultStream.Read(result, , result.Length);
data.datas = result;
resultStream.Dispose();
CanMoveNext = false;
}
}
}
return HttpListenerPostValueList;
}
catch (Exception ex)
{
return null;
}
} /// <summary>
/// 获取Post过来的参数和数据
/// </summary>
/// <returns></returns>
public PalletLableInfo GetPalletLableInfoValue()
{
try
{
var model = new PalletLableInfo(); Stream SourceStream = request.Request.InputStream;
var resultStream = new MemoryStream(); byte[] currentChunk = ReadFullAsBytes(SourceStream); model = Newtonsoft.Json.JsonConvert.DeserializeObject<PalletLableInfo>(Encoding.UTF8.GetString(currentChunk)); model.RequestTime = DateTime.Now;
return model;
}
catch (Exception ex)
{
return null;
}
}
}

4. Form调用:

//调用启动监听
HttpPostListener.BizLister(McConfig.Instance.Url);
      /// <summary>
/// 页面加载完成事件-实现自动打印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void wbr_htmPage_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//htmlEditor.Focus();
//var dom = wbr_htmPage.Document.DomDocument as IHTMLDocument2;
//bool res = false;
//if (this.wbr_htmPage.ReadyState == WebBrowserReadyState.Complete)
//{
// dom = wbr_htmPage.Document.DomDocument as IHTMLDocument2;
// dom.designMode = "On";
// res = dom.execCommand("FontName", true, "Arial");
// res = dom.execCommand("FontSize", true, 12);
//} //this.wbr_htmPage.ShowPrintDialog();
//this.wbr_htmPage.ShowPageSetupDialog();
this.wbr_htmPage.ShowPrintPreviewDialog();
// this.wbr_htmPage.Print(); if (wbr_htmPage.Document.Body != null)
{
// wbr_htmPage.Document.Body.Style = "zoom:50%;FontSize:0.84rm"; //foreach (var kVal in BizReStatus.MonitorLinks[McConfig.Instance.Url[0]].CurrPalletLableInfo.data)
//{
// //this.wbr_htmPage.Document.GetElementById(kVal.Key).OuterText = kVal.Value.ToString();
// this.wbr_htmPage.Document.All[kVal.Key].SetAttribute("value", kVal.Value.ToString());
//}
} this.wbr_htmPage.ShowPrintPreviewDialog(); this.wbr_htmPage.Print();
}

最新文章

  1. App单个页面的最佳文本框个数是多少个?
  2. 资源: CustomResource, ResourceDictionary, 加载外部的 ResourceDictionary 文件
  3. git的那点事---
  4. Cite a Website in Paper 论文中引用网页的格式
  5. PHP中使用数组指针函数操作数组示例
  6. 《Unix网络编程》卷2 读书笔记 第3章- System V IPC
  7. Jenkin+TestNG进行自动化测试执行
  8. MySQL 子查询 EXISTS 和 NOT EXISTS
  9. Muduo-Base-TimeStamp类
  10. 二叉树的建立与遍历(山东理工OJ)
  11. Swiftly语言学习1
  12. cephfs创建及挂载
  13. Tomcat去除端口号和项目名(转)
  14. 汇编指令-MRS(读)和MSR(写)指令操作CPSR寄存器和SPSR寄存器使用(1)
  15. maven 依赖中scope标签的配置范围详解
  16. 我的第一个python web开发框架(24)——系统重构与ORM
  17. Linux(CentOS6)系统安装Windows字体
  18. php开启xdebug扩展
  19. 分布式事务的CAP理论 与BASE理论
  20. 查询orcale运行的SQL语句记录

热门文章

  1. 【CF 718C】fibonacci
  2. 线段树(SegmentTree)基础模板
  3. java web 域对象
  4. Django-ORM和MySQL事务及三大范式介绍
  5. 【51nod1792】Jabby&#39;s segment tree
  6. wx小程序知识点(三)
  7. CSS样式,语法,添加方法,文本,字体
  8. gulp[13124]: c:\ws\src\node_contextify.cc:626: Assertion `args[1]-&gt;IsString()&#39; failed
  9. LOJ #6145. 「2017 山东三轮集训 Day7」Easy 点分树+线段树
  10. TTTTTTTTTTTTT CF Good Bye 2015 C- New Year and Domino(CF611C) 二维前缀