c#-4.0 – 使用带有TCP / IP接口的C#中执行的ESC / POS命令直接打印到热敏打印机

前端之家收集整理的这篇文章主要介绍了c#-4.0 – 使用带有TCP / IP接口的C#中执行的ESC / POS命令直接打印到热敏打印机前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在厨房打印机(Aclas KP71M)上实施ESC / POS(Epson销售点标准代码).
我有一个用户界面,POS用户将其字符串输入到用户界面,用户输入的字符串将被发送到打印机,打印机打印数据.
打印机与主机的接口使用以太网(100M)使用TCP / IP连接.我已经设法将每个必要的命令嵌入到C#方法中,我还在服务器/客户端C#上采用了一些示例代码
连接并尝试将其包含在我的连接中.
我现在面临的问题是我的代码似乎开始连接但它立即冻结
没有做任何事情并且停止了连接.如果有人可以纠正我,或者告诉我问题所在,或者让我知道如何继续,我将非常感激?
这是代码.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace ESC_POS
{
   public partial class Form1 : Form
   {
        public string tableNumber;
        public string itemOrdered;
        public string orderedQuantity;
        public string waiterName;
        public string orderDestination;
        public string orderNumber;

        const int MAX_CLIENTS = 10;

        public AsyncCallback pfnWorkerCallBack;
        private Socket m_mainSocket;
        private Socket[] m_workerSocket = new Socket[10];
        private int m_clientCount = 0;//Server declarations

        byte[] m_dataBuffer = new byte[10];
        IAsyncResult m_result;
        public AsyncCallback m_pfnCallBack;
        public Socket m_clientSocket;//Client declarations

        public Form1()
        {
            InitializeComponent();
            PC_IP.Text = GetIP();
            PRINTER_IP.Text = GetIP();
        }

        public void label1_Click(object sender,EventArgs e)
        {
        }

        public void Form1_Load(object sender,EventArgs e)
        {
        }   

        public void TableNumber_TextChanged(object sender,EventArgs e)
        {
            if (TableNumber.Text == "")
            {
                MessageBox.Show("Please enter the table number");
                return;
            }
            tableNumber = TableNumber.Text;
        }

        public void OrderedQuantitiy_TextChanged(object sender,EventArgs e)
        {
            if (OrderedQuantitiy.Text == "")
            {
                MessageBox.Show("Please enter the ordered quantity");
                return;
            }
            orderedQuantity = OrderedQuantitiy.Text;
        }

        public void WaiterName_TextChanged(object sender,EventArgs e)
        {
            if (WaiterName.Text == "")
            {
                MessageBox.Show("Please enter the waiter name");
                return;
            }
            waiterName = WaiterName.Text;
        }

        public void comboOrderDestination_SelectedIndexChanged(object sender,EventArgs e)
        {

            if (ItemOrdered.Text == "")
            {
                MessageBox.Show("Please select the order destiination");
                return;
            }
            orderDestination = comboOrderDestination.SelectedText;
        }

        public void OrderNumber_TextChanged(object sender,EventArgs e)
        {
            if (OrderNumber.Text == "")
            {
                MessageBox.Show("Please enter the order number");
                return;
            }
            orderNumber = OrderNumber.Text;
        }

        public void PrintButton_Click(object sender,EventArgs e)
        {
            try
            {   
                string[] printData = new string[6];
                printData[0]=tableNumber ;
                printData[1]= itemOrdered;
                printData[2]= orderedQuantity;
                printData[3]= waiterName;
                printData[4]= orderDestination;
                printData[5]= orderNumber;
                string richTextMessage = "";
                PrinterCommands printCmd = new PrinterCommands();
                printCmd.initializePrinter();
                PrinterCommands print = new PrinterCommands();

                for (int i = 0; i < printData.Length; i++)
                {
                    richTextMessage = printData[i]+" ";
                    richTextMessage = print.LineFeed().ToString();
                }
                Object objData = richTextMessage;


                byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
                if (m_clientSocket != null)
                {
                    m_clientSocket.Send(byData);
                }
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void textBox1_TextChanged(object sender,EventArgs e)
        {
        }

        public void PC_PORT_TextChanged(object sender,EventArgs e)
        {
        }

        public void PRINTER_IP_TextChanged(object sender,EventArgs e)
        {
        }

        public void PRINTER_PORT_TextChanged(object sender,EventArgs e)
        {
        }

        public void Connect_toPC_Click(object sender,EventArgs e)
        {
            // See if we have text on the IP and Port text fields
            // See if we have text on the IP and Port text fields
            if (PRINTER_IP.Text == "" || PRINTER_PORT.Text == "")
            {
                MessageBox.Show("IP Address and Port Number are @R_502_103@ to connect to the Server\n");
                return;
            }
            try
            {
                UpdateControlsPrinter(false);
                // Create the socket instance
                m_clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

                // Cet the remote IP address
                IPAddress ip = IPAddress.Parse(PRINTER_IP.Text);
                int iPortNo = System.Convert.ToInt16(PRINTER_PORT.Text);
                // Create the end point 
                IPEndPoint ipEnd = new IPEndPoint(ip,iPortNo);
                // Connect to the remote host
                m_clientSocket.Connect(ipEnd);
                if (m_clientSocket.Connected)
                {

                    UpdateControlsPrinter(true);
                    //Wait for data asynchronously 
                    WaitForData();
                }
            }
            catch (SocketException se)
            {
                string str;
                str = "\nConnection Failed,is the server running?\n" + se.Message;
                MessageBox.Show(str);
                UpdateControlsPrinter(false);
            }       
        }

        public void ItemOrdered_TextChanged_1(object sender,EventArgs e)
        {
            if (ItemOrdered.Text == "")
            {
                MessageBox.Show("Please enter the Item Ordered");
                return;
            }
        }

        public void Disconnect_toPC_Click(object sender,EventArgs e)
        {

            if (m_clientSocket != null)
            {
                m_clientSocket.Close();
                m_clientSocket = null;
             UpdateControlsPrinter(false);
            }
            Close();
        }

        public void Start_Listening_Click(object sender,EventArgs e)
        {
            try
            {
                // Check the port value
                if (PC_PORT.Text == "")
                {
                    MessageBox.Show("Please enter a Port Number");
                    return;
                }
                string portStr = PC_PORT.Text;
                int port = System.Convert.ToInt32(portStr);
                // Create the listening socket...
                m_mainSocket = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);
                IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any,port);
                // Bind to local IP Address...
                m_mainSocket.Bind(ipLocal);
                // Start listening...
                m_mainSocket.Listen(4);
                // Create the call back for any client connections...
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect),null);

                UpdateControls(true);

            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void Stop_Listening_Click(object sender,EventArgs e)
        {
            CloseSockets();
            UpdateControls(false);
            Close();
        }

        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        public void CloseSockets()
        {
            if (m_mainSocket != null)
            {
                m_mainSocket.Close();
            }
            for (int i = 0; i < m_clientCount; i++)
            {
                if (m_workerSocket[i] != null)
                {
                    m_workerSocket[i].Close();
                    m_workerSocket[i] = null;
                }
            }
        }

        public void WaitForData()
        {
            try
            {
                if (m_pfnCallBack == null)
                {
                    m_pfnCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
              //          theSocPkt.thisSocket = m_clientSocket;
                // Start listening to the data asynchronously
                m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer,theSocPkt.dataBuffer.Length,SocketFlags.None,m_pfnCallBack,theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }

        }

        public void WaitForData(System.Net.Sockets.Socket soc)
        {
            try
            {
                if (pfnWorkerCallBack == null)
                {
                    // Specify the call back function which is to be 
                    // invoked when there is any write activity by the 
                    // connected client
                    pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
                }
                SocketPacket theSocPkt = new SocketPacket();
                theSocPkt.m_currentSocket = soc;
                // Start receiving any data written by the connected client
                // asynchronously
                soc.BeginReceive(theSocPkt.dataBuffer,pfnWorkerCallBack,theSocPkt);
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public class SocketPacket
        {
            public System.Net.Sockets.Socket m_currentSocket;
            public byte[] dataBuffer = new byte[1];
        }

        public void UpdateControlsPrinter(bool connected)
        {
            Connect_toPC.Enabled = !connected;
            Disconnect_toPC.Enabled = connected;
            string connectStatus = connected ? "Connected" : "Not Connected";
           // textBoxConnectStatus.Text = connectStatus;
        }

        public void UpdateControls(bool listening)
        {
            Start_Listening.Enabled = !listening;
            Stop_Listening.Enabled = listening;
        }

        public void OnDataReceived(IAsyncResult asyn)
        {
            try
            {
                SocketPacket socketData = (SocketPacket)asyn.AsyncState;

                int iRx = 0;
                // Complete the BeginReceive() asynchronous call by EndReceive() method
                // which will return the number of characters written to the stream 
                // by the client
                iRx = socketData.m_currentSocket.EndReceive(asyn);
                char[] chars = new char[iRx + 1];
                System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
                int charLen = d.GetChars(socketData.dataBuffer,iRx,chars,0);
                System.String szData = new System.String(chars);
              //  richTextBoxReceivedMsg.AppendText(szData);

                // Continue the waiting for data on the Socket
                WaitForData(socketData.m_currentSocket);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }

        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object
                m_workerSocket[m_clientCount] = m_mainSocket.EndAccept(asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                WaitForData(m_workerSocket[m_clientCount]);
                // Now increment the client count
                ++m_clientCount;
                // Display this client connection as a status message on the GUI    
                String str = String.Format("Client # {0} connected",m_clientCount);
               // textBoxMsg.Text = str;

                // Since the main Socket is now free,it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect),null);
            }
            catch (ObjectDisposedException)
            {
                System.Diagnostics.Debugger.Log(0,"\n OnClientConnection: Socket has been closed\n");
            }
            catch (SocketException se)
            {
                MessageBox.Show(se.Message);
            }
        }
    }
}

解决方法

回答这个问题以防其他任何人出现同样的问题.这对我有用:
Socket clientSock = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);
clientSock.NoDelay = true;
IPAddress ip = IPAddress.Parse("192.168.0.18");
IPEndPoint remoteEP = new IPEndPoint(ip,9100);
clientSock.Connect(remoteEP);
Encoding enc = Encoding.ASCII;

// Line Feed hexadecimal values
byte[] bEsc = new byte[4];
bEsc[0] = 0x0A;
bEsc[1] = 0x0A;
bEsc[2] = 0x0A;
bEsc[3] = 0x0A;

// Send the bytes over 
clientSock.Send(bEsc);

// Sends an ESC/POS command to the printer to cut the paper
string output = Convert.tochar(29) + "V" + Convert.tochar(65) + Convert.tochar(0);
char[] array = output.tocharArray();
byte[] byData = enc.GetBytes(array);
clientSock.Send(byData);
clientSock.Close();
原文链接:https://www.f2er.com/csharp/96972.html

猜你在找的C#相关文章