移动手机端通过PC转接实现标签打印的解决方案
废话不多讲,由于种种原因项目上出现了移动手持录入标签信息通过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转接实现标签打印的解决方案的更多相关文章
- CSS3及JS简单实现选项卡效果(适配手机端和pc端)
想要适配手机端和pc端,有几种简单的方法,本人使用的是百分比分配的方法. *{ padding: 0; margin: 0; } body,html{ width: 100%; height: 100 ...
- PHP项目实现手机端和PC端的页面切换
目前访问页面的要切换成手机端和PC端,原理是通过对设备作出判断,显示不同的功能和页面. 如果手机端和PC端的功能结构不相同,一般会写两套系统,一套适用于PC端,一套适用于手机端. 如果功能相同,则只需 ...
- PHP判断是手机端还是PC端
function check_wap() { if (isset($_SERVER['HTTP_VIA'])) return true; if (isset($_SERVER['HTTP_X_NOKI ...
- 腾讯首页分辨手机端与pc端代码
腾讯首页分辨手机端与pc端代码 自己在做网页的时候在腾讯网首页借鉴的代码. 代码: <!-- 移动适配JS脚本 --> <script type="text/javascr ...
- 获取网页是手机端还是PC端访问
C#方式: /// <summary> /// 是否手机访问 /// </summary> /// <returns></returns> public ...
- vue-判断设备是手机端还是pc端
经常在项目中会有支持 pc 与手机端需求.并且pc与手机端是两个不一样的页面.这时就要求判断设置,根据不同的设置跳转不同的路由. [代码演示] 在 router/index.js 中有两个页面. ex ...
- php 判断是否手机端还是pc端
来自:https://www.cnblogs.com/webenh/p/5621890.html 用手机访问PC端WWW域名的时候,自动判断跳转到移动端,用电脑访问M域名手机网站的时候,自动跳转到PC ...
- 【转】自动识别是手机端还是pc端只用一行代码就搞定
<script type="text/javascript"> var mobileAgent = new Array("iphone", &quo ...
- js判断客户端是手机端还是PC端
封装函数: function isPC() { var userAgentInfo = navigator.userAgent; var Agents = ["Android", ...
随机推荐
- 19.8.8 flutter 学习之创建第一个可变的Widget
创建一个很简单的可变的Widget 效果就是点击字的时候会变化 完整代码: class CarPage extends StatefulWidget { @override _CarState cre ...
- 多项式FFT/NTT模板(含乘法/逆元/log/exp/求导/积分/快速幂)
自己整理出来的模板 存在的问题: 1.多项式求逆常数过大(尤其是浮点数FFT) 2.log只支持f[0]=1的情况,exp只支持f[0]=0的情况 有待进一步修改和完善 FFT: #include&l ...
- 3DES加解密类
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace GT.C ...
- 写在centos7 最小化安装之后
1.最小化安装之后首先解决联网问题(https://lintut.com/how-to-setup-network-after-rhelcentos-7-minimal-installation/) ...
- ASP.NET上传断点续传
IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头. 一. 两个必要响应头Accept-Ranges.ETag 客户端每次提交下载请求时,服务 ...
- poj 2559 Largest Rectangle(单调栈)
Largest Rectangle in a Histogram Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 26549 ...
- HGOI 20190705 题解
Problem A 树状数组 给出数x,一直执行x = x and (x+1)-1 直到 x=0 为止 询问这个数执行运算的次数. 这个数以二进制的形式表述出 x = s1 & s2 .... ...
- confluence -- 命令行备份还原
备份:confluence每日凌晨2:00都在 /data/atlassian/application-data/confluence/backups/ 下生成备份包,其中包括文档,附件,用户 还原: ...
- MiracleSnow网页设计HTML5+CSS3+JS全套视频教程
终于把这套课程讲完了,虽然时间隔了很长,但也算有始有终了,这是在YY讲课中我自己录的,讲了网页设计的基础,这也是我第一次给那么多人讲课,讲的不好多多包涵. 前几次视频和课件是分开的,后几次都打包在一起 ...
- 「POI 2010」Bridges
题目链接 戳我 \(Solution\) 看到"最大值最小",就知道应该要二分 二分之后,对于每个\(mid\),只要计算小于\(mid\)的边,然后在剩下的图中判断有无欧拉回路 ...