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