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();
|
}
|
}
|
|
|
}
|