首页 > 代码库 > 指令打印程序(通过Socket)

指令打印程序(通过Socket)

1、对应的IP
2、将打印的文本文件
 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.OutputStream;
 7 import java.net.InetSocketAddress;
 8 import java.net.Socket;
 9 
10 public class PrintBySocket
11 {
12 
13     private static String ip = "172.16.12.251";// 更改成网络打印机的IP
14 
15     private static int port = 9100;// 更改成网络打印机的端口
16 
17     private static int timeout = 1000;// 设置超时时间
18 
19     public static void main(String[] args)
20         throws Exception
21     {
22         String filepath = "C:\\RFID2.txt";// 指令文件存放的位置
23         File file = new File(filepath);
24         byte[] command = new byte[10];
25         String label = null;
26         if (file.exists())
27         {// 检查指令文件存在不存在
28             InputStream is = new FileInputStream(file);
29             ByteArrayOutputStream out = new ByteArrayOutputStream();
30             int len = 0;
31             while ((len = is.read(command)) > 0)
32             {
33                 out.write(
34                     command, 0, len);
35             }
36             // label = new String(out.toByteArray(),"utf-8");
37             label = new String(out.toByteArray(), "gbk");
38             System.out.println(label);
39         }
40         else
41         {// 指令文件不存在则直接返回
42             System.out.println("指令文件不存在");
43             return;
44         }
45 
46         Socket s = null;
47         OutputStream writer = null;
48         try
49         {
50             s = new Socket();
51             s.connect(new InetSocketAddress(ip, port));
52             s.setSoTimeout(timeout);
53             writer = s.getOutputStream();
54             byte[] bytes;
55             // bytes = label.getBytes("utf-8");
56             bytes = label.getBytes("gbk");
57             writer.write(
58                 bytes, 0, bytes.length);
59             writer.flush();
60         }
61         catch (IOException e)
62         {
63             throw new RuntimeException("试图连接到打印机的时候发生错误,请检查你的网络连接,并确认打印机已经开机!", e);
64         }
65         finally
66         {
67             if (writer != null)
68             {
69                 try
70                 {
71                     writer.close();
72                 }
73                 catch (Exception e)
74                 {
75                 }
76             }
77             if (s != null)
78             {
79                 try
80                 {
81                     s.close();
82                 }
83                 catch (Exception e)
84                 {
85                 }
86             }
87         }
88     }
89 }
View Code