废话不多讲,由于种种原因项目上出现了移动手持录入标签信息通过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. java web 域对象

    四大域对象 pagecontext  表示的是当前页面的域对象Request表示的是请求域中的对象session  表示的是一次会话中的对象application表示的是在一次tc启动到一次关闭的时候 ...

  2. 也来谈谈SQL SERVER 自定义函数~

    在使用SQL SERVER 数据库的时候,函数大家都应该用过,简单的比如 系统聚合函数 Sum(),Max() 等等.但是一些初学者编写自定义函数的时候,经常问起什么是表值函数,什么是标量值函数. 表 ...

  3. 最近老是有兄弟问我,Vue双向绑定的原理,以及简单的原生js写出来实现,我就来一个最简单的双向绑定,原生十行代码让你看懂原理

    废话不多说直接看效果图 代码很好理解,但是在看代码之前需要知道Vue双向绑定的原理其实就是基于Object.defineProperty 实现的双向绑定 官方传送门 这里我们用官方的话来说Object ...

  4. Acwing-278-数字组合(背包)

    链接: https://www.acwing.com/problem/content/280/ 题意: 给定N个正整数A1,A2,-,AN,从中选出若干个数,使它们的和为M,求有多少种选择方案. 思路 ...

  5. Matlab的基本矩阵运算

    (1)加减.数乘 >> a=[1,2;3,4];b=[5,6;7,8]; >> a+b ans = 6 8 10 12 >> a.*2 ans = 2 4 6 8 ...

  6. vue启动问题(You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore all warnings in a file.)

    解决vue启动出现: 在build/webpack.base.conf.js文件中,把...(config.dev.useEslint ? [createLintingRule()] : [])注释或 ...

  7. 通过喝水清晰简单了解I/O五大模型

    一般单次I/O请求会分为两个阶段,每个阶段对于I/O的处理方式是不同的 I/O会经历一个等待资源的阶段 阻塞,指的是在数据不可用时,I/O请求会一直阻塞,直到数据返回 数据不可用时,立即返回,直到被通 ...

  8. js 动态加载js 并执行

    function loadJS(url, success) { var domScript = document.createElement('script'); domScript.src = ur ...

  9. BZOJ 4154: [Ipsc2015]Generating Synergy KDtree+dfs序

    多组数据真tm恶心~ 把 $dfs$序和深度分别看作横纵坐标,然后用 $KDtree$ 数点就可以了~ #include <cstdio> #include <cstring> ...

  10. Linux服务器pxe+kickstart部署无人值守安装

    一.    使用光盘镜像安装好一台Redhat6.8系统的虚拟机(图形化界面) 二.    部署相关服务程序 1.     安装并配置dhcpd服务程序 a)安装dhcp服务程序 b)对dhcp服务进 ...