using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace POSPrinter
{///    ///   POSPrinter的摘要说明。///   此类处理网络打印,使用了IP端口.///    publicclassNetPOSPrinter{string ipPort ="127.0.0.1";publicNetPOSPrinter(){}publicNetPOSPrinter(string IpPort){this.ipPort = IpPort;//打印机端口 }///    ///   输出文字到打印机 ///    ///    要打印的内容  publicvoidPrintLine(string str){//建立连接IPAddress ipa = IPAddress.Parse(ipPort);IPEndPoint ipe =newIPEndPoint(ipa,9100);//9100为小票打印机指定端口Socket soc =newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);soc.Connect(ipe);//string str= "hello,123456789,大家好! ";byte[] b = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);soc.Send(b);soc.Close();}publicvoidPrintPic(Bitmap bmp){//把ip和端口转化为IPEndPoint实例IPEndPoint ip_endpoint =newIPEndPoint(IPAddress.Parse(ipPort),9100);//创建一个SocketSocket socket =newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//连接到服务器socket.Connect(ip_endpoint);//应对同步Connect超时过长的办法,猜测应该是先用异步方式建立以个连接然后,//确认连接是否可用,然后报错或者关闭后,重新建立一个同步连接                    //socket.SendTimeout = 1000;//初始化打印机,并打印Byte[] byte_send = Encoding.GetEncoding("gb18030").GetBytes("\x1b\x40");//发送测试信息socket.Send(byte_send, byte_send.Length,0);byte[] data =newbyte[]{0x1B,0x33,0x00};socket.Send(data, data.Length,0);data[0]=(byte)'\x00';data[1]=(byte)'\x00';data[2]=(byte)'\x00';// Clear to Zero.Color pixelColor;// ESC * m nL nH 点阵图byte[] escBmp =newbyte[]{0x1B,0x2A,0x00,0x00,0x00};escBmp[2]=(byte)'\x21';//nL, nHescBmp[3]=(byte)(bmp.Width %256);escBmp[4]=(byte)(bmp.Width /256);// datafor(int i =0; i <<>(bmp.Height /24)+1; i++){socket.Send(escBmp, escBmp.Length,0);for(int j =0; j <<> bmp.Width; j++){for(int k =0; k <<>24; k++){if(((i *24)+ k)<<> bmp.Height)// if within the BMP size{pixelColor = bmp.GetPixel(j,(i *24)+ k);if(pixelColor.R ==0){data[k /8]+=(byte)(128>>(k %8));}}}socket.Send(data,3,0);data[0]=(byte)'\x00';data[1]=(byte)'\x00';data[2]=(byte)'\x00';// Clear to Zero.}                byte_send = Encoding.GetEncoding("gb18030").GetBytes("\n");//发送测试信息socket.Send(byte_send, byte_send.Length,0);}// databyte_send = Encoding.GetEncoding("gb18030").GetBytes("\n");//发送测试信息socket.Send(byte_send, byte_send.Length,0);socket.Close();}///    ///   打开钱箱 ///    publicvoidOpenCashBox(){IPAddress ipa = IPAddress.Parse(ipPort);IPEndPoint ipe =newIPEndPoint(ipa,9100);//9100为小票打印机指定端口Socket soc =newSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);soc.Connect(ipe);char[] c ={ Convert.ToChar(27),'p', Convert.ToChar(0), Convert.ToChar(60), Convert.ToChar(255)};byte[] b = System.Text.Encoding.GetEncoding("GB2312").GetBytes(c);soc.Send(b);soc.Close();}}}