POS打印机系列之 = 网口
生活随笔
收集整理的這篇文章主要介紹了
POS打印机系列之 = 网口
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
在熟悉了串口、并口打印后,網(wǎng)口打印就容易明白了。與前兩者的區(qū)別是:網(wǎng)口通過socket通信。
/// <summary>/// 網(wǎng)口通信/// </summary>public interface INetContact : IPortContact{ActionResult Connect(string ip, int port);}public class NetContact : INetContact{Socket _socket = null;private readonly int TryReconnectTimes = 3;private readonly int Timeout = 5000;public bool Opened { get; set; }/// <summary>/// Connects the specified ip.連接網(wǎng)口打印機(jī)/// </summary>/// <param name="ip">The ip.</param>/// <param name="port">The port.</param>/// <returns></returns>public ActionResult Connect(string ip, int port){if (string.IsNullOrEmpty(ip)){return new ActionResult(false, "網(wǎng)口打印機(jī)未指定有效IP地址");}// 先關(guān)閉if (Opened){_socket.Close();Opened = false;}try{for (int i = 0; i < TryReconnectTimes; i++){// 創(chuàng)建socket并連接到服務(wù)器_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);var result = _socket.BeginConnect(IPAddress.Parse(ip), port, null, null);bool success = result.AsyncWaitHandle.WaitOne(Timeout, true);if (success){try{_socket.EndConnect(result);Opened = true;return new ActionResult(true);}catch (SocketException){continue;}}else{_socket.Close();}}return new ActionResult(false, string.Format("打印機(jī)IP:{0}連接超時(shí),請(qǐng)檢查網(wǎng)絡(luò)是否存在異常!", ip));}catch (Exception ex){return new ActionResult(false,string.Format("連接網(wǎng)口打印機(jī)失敗:{0}", ex.Message));}}/// <summary>/// Sends the specified data.發(fā)送文本到打印機(jī)/// </summary>/// <param name="data">The data.</param>/// <returns></returns>public int Write(string data){return Write(Encoding.GetEncoding("gb2312").GetBytes(data));}/// <summary>/// Sends the specified data.發(fā)送byte數(shù)據(jù)到打印機(jī)/// </summary>/// <param name="data">The data.</param>/// <returns></returns>public int Write(byte[] data){if (!Opened){return 0;}int offset = 0;try{int timeout = TimeSpan.FromSeconds(10).Milliseconds;int waitTime = TimeSpan.FromMilliseconds(30).Milliseconds;_socket.SendTimeout = timeout;while (offset != data.Length){if (_socket.Poll(waitTime, SelectMode.SelectWrite)){offset += _socket.Send(data, offset, data.Length - offset, SocketFlags.None);}}}catch (Exception ex){throw new Exception(string.Format("向網(wǎng)口打印機(jī)發(fā)送數(shù)據(jù)失敗:{0}", ex.Message));}return offset;}/// <summary>/// Closes this connection.關(guān)閉網(wǎng)絡(luò)連接/// </summary>public void Close(){if (Opened){_socket.Shutdown(SocketShutdown.Both);_socket.Close();Opened = false;}_socket = null;}public byte[] Read(int length){byte[] buffer = null;if (Opened){buffer = new byte[length];_socket.Receive(buffer);}return buffer;}} View Code?
轉(zhuǎn)載于:https://www.cnblogs.com/zzq417/p/Print_NetPort.html
總結(jié)
以上是生活随笔為你收集整理的POS打印机系列之 = 网口的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2018最新IntelliJ IDEA全
- 下一篇: 贪吃蛇java 暂停_Java实现贪吃蛇