/**
* 连接硬件获取数据
*/
public class TCPClient {
//IP地址
private String host = "192.168.4.201";
//电子秤本地端口
private Integer port = 20108;
//TCP 连接
private Socket socket = null;
public static void main(String[] args) throws Exception {
//创建对象
TCPClient tcpClient = new TCPClient();
try {
//调用 连接 + 获取的方法
tcpClient.client();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从连接中尝试获取数据
*
* @throws Exception
*/
public void client() throws Exception {
判断连接是否创建,是否已经链接
if (socket != null && socket.isConnected()) {
//创建连接并且赋值给 全局连接
socket();
//开启接收紧急数据
socket.setOOBInline(true);
//创建一个 重连线程
Thread checkThread = new Thread(new Runnable() {
@Override
public void run() {
//一直循环
while (true) {
try {
//发送紧急数据,在任何OutputStream之后和之前发送
socket.sendUrgentData(0XFF);
} catch (IOException e) {
//如果异常就关闭连接,再重新创建连接
try {
//关闭连接
socket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
//重新创建连接
socket = new Socket(host, port);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
try {
//线程睡眠3秒,让下面的 获取数据线程启动 readtThread
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
//线程启动
checkThread.start();
//创建一个 获取数据线程
Thread readtThread = new Thread(new Runnable() {
@Override
public void run() {
//创建一个 空的字符串
String line = null;
while (true) {
//返回套接字的关闭状态,关闭返回true
if (socket.isClosed()) {
try {
//睡眠3秒,让上面的 重连线程启动 checkThread
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//跳出循环
continue;
}
//获取传递过来的数据
// try (BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"))) {
// while ((line = buffer.readLine()) != null) {
// line = getSubUtilSimple(line);
// System.out.println(line);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//读取服务器发回的数据,使用socket套接字对象中的字节输入流
try {
InputStream inputStream = socket.getInputStream();
byte[] data = new byte[1024];
int len = inputStream.read(data);
//将获取到电子秤传递过来的数据
String s1 = new String(data,0,len);
//调用字符串分割的方法
line = getSubUtilSimple(s1);
System.out.println("字符串分割后的数据:" + line);
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
readtThread.start();
}else {
//调用创建连接的方法,并且赋值给 全局连接
socket();
//递归,重新调用方法
client();
}
}
/**
* 定义一个方法,创建与电子秤的连接
* @return
*/
public boolean socket() {
//
try {
socket = new Socket(host, port);
if (socket.isConnected() && socket != null){
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 分割字符串 某个字符串和某个字符串之间的数据
*
* @param s1 需要分割的字符串
* <p>
* 获取到的值为: + 7.12 kg \t \n
* @return
*/
public static String getSubUtilSimple(String s1) {
//定义一个变量,
String kg = null;
//判断是否包含 + ,正常的数据
if (s1.contains("+")) {
//赋值
kg = s1;
//获得第一个 + 的位置
int index = s1.indexOf("+") + 1;
//获取第一个 g 的位置
int end = s1.indexOf(".");
//字符串分割
kg = kg.substring(index, end);
//去掉字符串的空格
kg = kg.replace(" ", "") + "kg";
return kg;
}
return s1;
}
}