关闭

C#利用pos命令操作网口打印机的方法

标签: c#exceptionbuffersocketbytestream
2798人阅读 评论(2) 收藏 举报
分类:

使用POS命令操作网口打印机的好处在于免驱动并且打印速度较快.

方法一使用TcpClient类

关键代码

  Int32 port = 9100;
  string bigFont =((char)27).ToString() + ((char)33).ToString() + ((char)213).ToString();//放大字体       
            TcpClient client = new TcpClient();
            try
            {
                client.Connect("172.30.168.100", port);

                Byte[] data = System.Text.Encoding.Default.GetBytes(bigFont);
                NetworkStream stream = client.GetStream();
                stream.Write(data, 0, data.Length);

                data = System.Text.Encoding.Default.GetBytes(bigFont);
                stream.Write(data, 0, data.Length);
                data = System.Text.Encoding.Default.GetBytes("打印机测试/n");
                stream.Write(data, 0, data.Length);
                data = System.Text.Encoding.Default.GetBytes("-             -/n");
                stream.Write(data, 0, data.Length);
                data = System.Text.Encoding.Default.GetBytes("-             -/n");
                stream.Write(data, 0, data.Length);
                stream.Close();
               
            }
            catch (Exception ex)
            {

                //如果打印机没开或者异常,在此处增加处理代码,我通常是把异常数据放到一个DataTable中,加个Timer来判断打印机正常就把

                //数据发给打印机并从表中移除.

                //打印机缺纸或者纸匣打开时,不会出现异常,不用特殊代码判断,数据不会丢失.
            }
            finally
            {
                client.Close();
            }

//-------------------------------------------------------------------------------------------------------------------------------------------

方法二使用Socket类

    Socket sendSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sendSocket.Connect("172.30.168.100", 9100);

                byte[] buffer = Encoding.Default.GetBytes(bigFont);

                sendSocket.Send(buffer);
                buffer = Encoding.Default.GetBytes("测试打印机/n");
                sendSocket.Send(buffer);
                sendSocket.Shutdown(SocketShutdown.Both);
             
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sendSocket.Close();
            }

这两种方法均可实现免驱网口打印.

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22743次
    • 积分:423
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:0篇
    • 译文:0篇
    • 评论:11条
    文章分类
    最新评论