@socket来通讯485转网络
通过socket来通讯485转网络
这是一个通过socket来通讯硬件的方法,抓取硬件传来的数据进行输入,并且实时数据传输。第一次写博客直接就放代码了。
创建DatagramSocket对象
static String responseMsg = "";
private String sendAndReceive(String ip, int port, String msg) {
try {
//创建客户端的DatagramSocket对象,不必传入地址和对象
client = new DatagramSocket();
byte[] sendBytes = hexStrToBytes(msg.replaceAll(" ", ""));
System.out.println();
//封装要发送目标的地址
InetAddress address = InetAddress.getByName(ip);
//封装要发送的DatagramPacket的对象,由于要发送到目的主机,所以要加上地址和端口号
DatagramPacket sendPacket = new DatagramPacket(sendBytes,sendBytes.length,address,port);
try {
//发送数据
client.send(sendPacket);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("数据发送成功:" + msg);
byte[] responseBytes = new byte[1024];
//创建响应信息的DatagramPacket对象
DatagramPacket responsePacket = new DatagramPacket(responseBytes,1024);
try {
//等待响应信息,同服务端一样,客户端也会在这一步阻塞,直到收到一个数据包
client.receive(responsePacket);
//client.send(responsePacket);
}catch (Exception e){
e.printStackTrace();
}
System.out.println("数据读取成功:" + msg);
//解析数据包内容
responseMsg = bytesToHexString(responsePacket.getData(),responsePacket.getLength());
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭客户端
if(client != null){
client.close();
client = null;
}
转16进制
因为我这边的传感器只接收16进制的所以我要转一下
private byte[] hexStrToBytes(String hexStr) {
if(null == hexStr || "".equals(hexStr)) {
return null;
}
if(0 != hexStr.length() % 2) {
hexStr = "0" + hexStr;
}
char[] chars = hexStr.toCharArray();
int len = chars.length/2;
byte[] bytes = new byte[len];
for (int i = 0; i < len; i++) {
int x = i * 2;
bytes[i] = (byte)Integer.parseInt(String.valueOf(new char[]{chars[x], chars[x+1]}), 16);
}
return bytes;
}
private String bytesToHexString(byte[] bytes, int length) {
if(null == bytes || bytes.length < length) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
String strHex = Integer.toHexString(bytes[i]);
if(strHex.length() > 3) {
sb.append(strHex.substring(6));
} else {
if(strHex.length() < 2) {
sb.append("0" + strHex);
} else {
sb.append(strHex);
}
}
}
return sb.toString();
}
发送指令
因为我这个需要给传感器发送一个指令,传感器才会返回数据
String msg = “e0 05 07 02 4b”;,这个指令是商家给的
UDPClient client = new UDPClient();
String msg = "e0 05 07 02 4b";
System.out.println("发送命令:" + msg);
String sendAndReceive="as";
sendAndReceive = client.sendAndReceive("192.168.0.189",6000, msg);
System.out.println(sendAndReceive);
//湿度
String humidity = responseMsg.substring(6,10);
BigInteger bigint=new BigInteger(humidity, 16);
int intValue = bigint.intValue();
System.out.println("湿度:"+intValue/10.0+"%RH");
//温度
String temperature = responseMsg.substring(10,14);
BigInteger bigint1=new BigInteger(temperature, 16);
int intValue1 = bigint1.intValue();
System.out.println("温度:"+intValue1/10.0+"℃"); }
我也是公司最近需要才开始学这个 , 就分享一下,有大佬一起研究也行,qq 1326496243