废话不多讲,由于种种原因项目上出现了移动手持录入标签信息通过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();
}

移动手机端通过PC转接实现标签打印的解决方案的更多相关文章

  1. CSS3及JS简单实现选项卡效果(适配手机端和pc端)

    想要适配手机端和pc端,有几种简单的方法,本人使用的是百分比分配的方法. *{ padding: 0; margin: 0; } body,html{ width: 100%; height: 100 ...

  2. PHP项目实现手机端和PC端的页面切换

    目前访问页面的要切换成手机端和PC端,原理是通过对设备作出判断,显示不同的功能和页面. 如果手机端和PC端的功能结构不相同,一般会写两套系统,一套适用于PC端,一套适用于手机端. 如果功能相同,则只需 ...

  3. PHP判断是手机端还是PC端

    function check_wap() { if (isset($_SERVER['HTTP_VIA'])) return true; if (isset($_SERVER['HTTP_X_NOKI ...

  4. 腾讯首页分辨手机端与pc端代码

    腾讯首页分辨手机端与pc端代码 自己在做网页的时候在腾讯网首页借鉴的代码. 代码: <!-- 移动适配JS脚本 --> <script type="text/javascr ...

  5. 获取网页是手机端还是PC端访问

    C#方式: /// <summary> /// 是否手机访问 /// </summary> /// <returns></returns> public ...

  6. vue-判断设备是手机端还是pc端

    经常在项目中会有支持 pc 与手机端需求.并且pc与手机端是两个不一样的页面.这时就要求判断设置,根据不同的设置跳转不同的路由. [代码演示] 在 router/index.js 中有两个页面. ex ...

  7. php 判断是否手机端还是pc端

    来自:https://www.cnblogs.com/webenh/p/5621890.html 用手机访问PC端WWW域名的时候,自动判断跳转到移动端,用电脑访问M域名手机网站的时候,自动跳转到PC ...

  8. 【转】自动识别是手机端还是pc端只用一行代码就搞定

    <script type="text/javascript"> var mobileAgent = new Array("iphone", &quo ...

  9. js判断客户端是手机端还是PC端

    封装函数: function isPC() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", ...

随机推荐

  1. php检测函数是否存在函数 function_exists

    php检测函数是否存在函数 function_exists 语法 bool function_exists ( string $function_name )检查的定义的函数的列表,同时内置(内部)和 ...

  2. Mongodb索引和执行计划 hint 慢查询

    查询索引 索引存放在system.indexes集合中 > show tables address data person system.indexes 默认会为所有的ID建上索引 而且无法删除 ...

  3. angularJs select ng-selected默认选中遇到的坑

    本人,程序员妹子一枚,,,,名字中有萌字,简称萌妹子哈,,,首先贴出代码: 同样的方式,用ng-selected用来做回显,但是结果让萌妹我很是诧异,第一个“模板类型”那里的select可正常回显,第 ...

  4. 【CF1187E】Tree Painting

    题目大意:给定一棵 N 个点的树,初始全是白点.要求你做 N 步操作,每一次选定一个与一个黑点相隔一条边的白点,将它染成黑点,然后获得该白点被染色前所在的白色联通块大小的权值.第一次操作可以任意选点, ...

  5. 三大方面,分析 to B和 to C产品的区别

    作为互联网从业者,我们经常听到to B(或2B)和to C(或2C)两个概念.to B即面向企业客户,to C即面向普通用户.只要是互联网人基本都懂知道这两个概念,但如果别人再问“to B和to C产 ...

  6. 使用SpringAOP实现事务(声明式事务管理、零配置)

    前言: 声明式事务管理建立在AOP之上的.其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务.声明式事务最大的优点就是不需要通过编 ...

  7. dirname命令和basename命令

    dirname返回文件所在目录路径,而basename则相反,去掉路径返回最后的文件名. direname: 用途 从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的 ...

  8. .net中[Serializable]序列化的应用

    原文链接:https://blog.csdn.net/wanlong360599336/article/details/9222459 浅析.NET中的Serialization 摘要 本文简要介绍了 ...

  9. Codeforces Round #325 (Div. 2) B. Laurenty and Shop 有规律的图 暴力枚举

    B. Laurenty and Shoptime limit per test1 secondmemory limit per test256 megabytesinputstandard input ...

  10. jmxtrans + influxdb + granafa 监控套件使用手册

    需求说明 随着大数据组件的日益完善,需要随时随地保持各个组件的日常运行,对各个组件的监控势在必行.为了减少运维部门的负担,通过筛选,我们使用 jmxtrans + influxdb + granafa ...