cl
2024-01-19 e0fac38b26845f25de479783e0c76cf12a5311e0
提交 | 用户 | 时间
71e81e 1 package cn.stylefeng.guns.modular.WebSocket;
2
3 import org.springframework.boot.ApplicationArguments;
4 import org.springframework.boot.ApplicationRunner;
5 import org.springframework.stereotype.Component;
6
7 import java.io.InputStream;
8 import java.io.OutputStream;
9 import java.net.Socket;
10
11 //@Component
12 public class TcpTest implements ApplicationRunner {
13
14     public void run(ApplicationArguments args) throws Exception {
15         //采用TelnetClient方式链接
16 //        TelnetClient tcpNet = new TelnetClient();
17         //采用Socket方式链接
18         Socket tcpNet = new Socket();
19         try {
20 //            tcp访问地址和端口
21             //采用TelnetClient方式链接
22 //            tcpNet.connect("127.0.0.1", 30311);
23 //            InputStream inputStream = tcpNet.getInputStream();
24             //采用Socket方式链接
25             tcpNet = new Socket("192.168.0.235", 60000);
26             InputStream inputStream = tcpNet.getInputStream();
27             byte[] b = new byte[1024];
28             int size;
29             while (true) {
30                 System.out.println("----------获取TCP信息开始----------");
31                 size = inputStream.read(b);
32                 String aa = new String(b, 0, size);
33                 System.out.println("tcp获取字符长度:" + size);
34                 System.out.println("tcp获取的条码:" + aa);
35                 //建立客户端信息输出流(客户端向服务端发送信息)
36                 OutputStream pt = tcpNet.getOutputStream();
37                 String printText = "客户端已成功接收信息!";
38                 pt.write(printText.getBytes());
39                 if(size>7){
40                     WebSocketService.sendMessage("badao",aa);
41                 }else {
42                     WebSocketService.sendMessage("badao2",aa);
43                 }
44             }
45
46         } catch (Exception e) {
47             e.printStackTrace();
48             System.out.println("++++++故障重新访问++++");
49             //断开tcp后自动重新链接
50             //断开后两秒后重新链接tcp  Socket方式
51             tcpNet.connect(tcpNet.getRemoteSocketAddress(), 2000);
52             //断开后重新链接tcp  TelnetClient方式
53             //tcpNet.disconnect();
54         }
55     }
56
57
58 }