POS打印机系列之 => 网口

在熟悉了串口、并口打印后,网口打印就容易明白了。与前两者的区别是:网口通过socket通信。

    /// <summary>
    /// 网口通信
    /// </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.连接网口打印机
        /// </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, "网口打印机未指定有效IP地址");
            }

            // 先关闭
            if (Opened)
            {
                _socket.Close();
                Opened = false;
            }

            try
            {
                for (int i = 0; i < TryReconnectTimes; i++)
                {
                    // 创建socket并连接到服务器
                    _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("打印机IP:{0}连接超时,请检查网络是否存在异常!", ip));
            }
            catch (Exception ex)
            {
                return new ActionResult(false,string.Format("连接网口打印机失败:{0}", ex.Message));
            }
        }

        /// <summary>
        /// Sends the specified data.发送文本到打印机
        /// </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.发送byte数据到打印机
        /// </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("向网口打印机发送数据失败:{0}", ex.Message));
            }
            return offset;
        }

        /// <summary>
        /// Closes this connection.关闭网络连接
        /// </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

 

posted @ 2013-07-17 11:27  zzq417  阅读(405)  评论(0编辑  收藏  举报