移动手机端通过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", ...
随机推荐
- nginx理论基础
- 使用nfs制作动态分配存储卷
参考文献:https://yq.aliyun.com/articles/613036 相对于静态存储, 动态存储的优势: ● 管理员无需预先创建大量的PV作为存储资源; ● 静态存储需要用户申请PVC ...
- Django-ORM和MySQL事务及三大范式介绍
Django中操作操作数据库这里需要改一个数据: 模型层:就是与跟数据库打交道 ORM查询: 一.单表操作必知必会13条: orm默认都是惰性查询: 1.all() 查询所有 2.filter() 筛 ...
- C++关于构造函数 和 析构函数 能否抛出异常的讨论
构造函数和析构函数分别管理对象的建立和释放,负责对象的诞生和死亡的过程.当一个对象诞生时,构造函数负责创建并初始化对象的内部环境,包括分配内存.创建内部对象和打开相关的外部资源,等等.而当对象死亡时, ...
- 24. ClustrixDB 持久性配置文件
这些持久性选项不适用于内存中的表.有关更多信息,请参见内存表. ClustrixDB提供了一个选项,通过指定如何提交事务并使其持久,从而提高性能.当提交成功通知应用程序时,用户可以在提交过程中指定提交 ...
- mybatis-plus-generator 实践
package com.huixiaoer.ant.generator; import com.baomidou.mybatisplus.annotation.DbType; import com.b ...
- react-router-dom 实现左侧导航
1.介绍react-router-dom https://reacttraining.com/react-router/web/example/basic 这个官网有很多栗子可以练手 1.1 Hash ...
- Mybatis笔记总结
第一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...
- javaScrpit插件学习制作
最近一直在学习javaScrpit插件制作,前几天学习制作了一个插件但存在严重缺陷. javaScrpit插件写法多种多样通过这几天的学习终于找到了适合自己的方法.前几天的缺陷也得到了解决.下面我们用 ...
- 深入理解Vuex 模块化(module)
todo https://www.jb51.net/article/124618.htm