This code requests from the command line an IP address or an host name, opens a TCP connexion on the corresponding machine, and write some text over the connection. Printed text is formatted using Epson® ESC/POS commands.
To test this code, create a C# command line application project under Microsoft Visual Studio, then replace the main file contents by this code.
using System; using System.Text; using System.Net.Sockets; namespace EthPosTcpSample { class Program { const char ESC = '\x1b'; const char FS = '\x1c'; const char GS = '\x1d'; static void TcpPrint(string host, byte[] data) { Socket s = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); s.Connect(host, 9100); s.Send(data); s.Disconnect(false); } static byte[] GetPrintData(string host) { StringBuilder sb = new StringBuilder(); // Initialize printer sb.Append(ESC + "@"); // Align center sb.Append(ESC + "a" + (char)1); // Use bold sb.Append(ESC + "E" + (char)1); // Add header text sb.Append("Active+ Software\n"); sb.Append("https://www.activeplus.com\n\n"); // Revert to align left and normal weight sb.Append(ESC + "a" + (char)0); sb.Append(ESC + "E" + (char)0); // Format some text sb.Append("This sample text is sent from a C# program\n"); sb.AppendFormat("to Ethernet POS machine '{0}'.\n\n", host); sb.Append("Regards,\nThe Active+ Software team\n"); // Feed and cut paper sb.Append(GS + "V\x41\0"); return Encoding.Default.GetBytes(sb.ToString()); } static void Main(string[] args) { Console.Write("Please enter a hostname or IP: "); string host = Console.ReadLine(); Console.WriteLine(); try { byte[] data = GetPrintData(host); TcpPrint(host, data); Console.WriteLine( "{0} bytes successfully sent to Ethernet POS machine '{1}'", data.Length, host); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } } } }
Download tcpip.cs