本示例使用设备:实时网络双门双向门禁控制板可二次编程控制网络继电器远程开关-淘宝网 (taobao.com)
package UdpDemo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.net.*;
import java.util.*;
//udp传输: 接收
/**步骤:---
* 1、建立udp socket,设置接收端口
* 2、预先创建数据存放的位置,封装
* 3、使用receive阻塞式接收
* 4、关闭资源
* */
public class PosDemo {
public static void main(String[] args) throws Exception{
//Scanner input = new Scanner(System.in);
String MyIpAdd=getIP(); //获取电脑网卡IP
InetAddress Addip=InetAddress.getByName(MyIpAdd) ;
DatagramSocket s = new DatagramSocket(39192); /** 1、建立udp socket端点 */
System.out.println("当前软件绑定的网卡:"+MyIpAdd+"\n\n");
String SendInfStr="000";
byte[] SendBuf = SendInfStr.getBytes(); /** 2、提供发送数据,封装打包 000 为搜索在线设备的指令 */
DatagramPacket dp = new DatagramPacket(SendBuf, SendBuf.length, InetAddress.getByName("255.255.255.255"), 39192);
try {
s.send(dp);
System.out.println("SendTo ip::255.255.255.255\nport::39192\ndata::"+SendInfStr+"\n\n");
} catch (IOException e) {
System.out.println("发送失败: ");
e.printStackTrace();
}
boolean i=true;
while(i){
String DevRecFramesStr;
String DevBufferIpAddrStr;
String DevBufferRemoteAddrStr;
String DevBufferMachinStr;
String DevBufferDatetimeStr;
String DevBufferSerialNumStr;
String DevBufferCardidStr;
String DevBufferUseMoneryStr;
String DevBufferUseTimeStr;
String DevBufferStaryStr;
String DevBufferRecordAddStr;
String DevBufferAllNoStr;
String DevBufferInputKeyStr;
String DevBufferMaskStr;
String DevBufferGatewayStr;
String DevBufferGatewayStrMAC;
String DevBufferRemoteAddrMACStr;
String DevBufferPort;
String DevBufferNumberDecStr;
String DevBufferMACSearchStr;
String DevBufferCommandStr;
String DevBufferReaderStr;
String DevBufferDoorNoStr;
String DevBufferDelayStr;
String DevBufferPasswPropStr;
String DevBufferPassWStr;
String DevBufferQrcodeInfStr;
int j;
byte [] bbuf = new byte [1024]; /**3、预先创建接收数据存放的位置,封装*/
DatagramPacket rdp = new DatagramPacket(bbuf,bbuf.length);
s.receive(rdp); /**4、使用receive阻塞式接收*/
String ReceiveDataStr=new String(rdp.getData());
String RemoteHostIP=rdp.getAddress().getHostAddress();
int RemotePort=rdp.getPort();
System.out.println("From ip::"+rdp.getAddress().getHostAddress()+"\nport::"+rdp.getPort()+"\ndata::"+ReceiveDataStr+"\n\n");
String[] strArr = ReceiveDataStr.split("\\,"); /*分割接收到的数据后再分析、处理、返回指令 */
switch(strArr[0]){
case "100": /*设备接收到搜索指令后返回的设备信息*/
if(strArr.length<9){
DevBufferIpAddrStr= strArr[1]; /*终端IP*/
DevBufferMaskStr= strArr[2]; /*掩码*/
DevBufferGatewayStr= strArr[3]; /*网关*/
DevBufferRemoteAddrStr= strArr[4]; /*远程服务器IP*/
DevBufferPort= strArr[5]; /*端口*/
DevBufferNumberDecStr= strArr[6]; /*设备序号*/
}else{
DevBufferIpAddrStr= strArr[1]; /*终端IP*/
DevBufferMaskStr= strArr[2]; /*掩码*/
DevBufferGatewayStr= strArr[3]; /*网关*/
DevBufferGatewayStrMAC= strArr[4]; /*网关MAC*/
DevBufferRemoteAddrStr= strArr[5]; /*远程服务器IP*/
DevBufferRemoteAddrMACStr= strArr[6]; /*远程服务器IPMAC*/
DevBufferMACSearchStr= strArr[7]; /*MAC搜索标识*/
DevBufferPort= strArr[8]; /*端口*/
DevBufferNumberDecStr= strArr[9]; /*设备模块序号*/
if(strArr.length>10){
DevBufferSerialNumStr= strArr[10]; /*设备唯一硬件序号*/
}
if(DevBufferRemoteAddrStr.compareTo("255.255.255.255")!=0 && DevBufferRemoteAddrStr.compareTo(MyIpAdd)!=0 ){
System.out.println("消费机的远程服务器IP不是指向当前网卡,请在消费机上 功能1>\7IP地址及端口设定 设定正确的网络参数!\n\n");
int Netcode=0;
Netcode=Netcode+1; //+1 表示服务器MAC自动搜索 否则服务器MAC锁定
Netcode=Netcode+2; //+2 表示网关MAC自动搜索 否则网关MAC锁定
Netcode=Netcode+4; //+4 表示DHCP可自动获取IP 否则指定IP
Netcode=Netcode+8; //+8 表示允许存储自动获取可用的IP 否则不存储
//根据现场的网络环境修改以下网络参数并传送到消费机上
//修改设备网络参数 消费机IP 掩码 网关 网关MAC 远程服务器IP(广播) 远程服务器MAC IP获取方式及MAC搜索方式 通讯端口 设备模块序号
SendInfStr="004,"+DevBufferIpAddrStr+","+DevBufferMaskStr+","+DevBufferGatewayStr+","+DevBufferGatewayStrMAC+",255.255.255.255,"+DevBufferRemoteAddrMACStr+","+ Integer.toString(Netcode).trim()+","+DevBufferPort+","+DevBufferNumberDecStr ;
SendInfToDiv(s,SendInfStr,RemoteHostIP,RemotePort); //修改消费机网络参数的指令
}
}
break;
case "101": /*有设备开机的信号*/
DevRecFramesStr = strArr[1]; /*包序列号 */
DevBufferIpAddrStr = strArr[2]; /*终端IP */
DevBufferRemoteAddrStr = strArr[3]; /*远程电脑指机IP*/
DevBufferMachinStr = strArr[4]; /*机号*/
DevBufferDatetimeStr = strArr[5]; /*日期时间*/
if(strArr.length>6){ /*2018年以后的设备有唯一硬件序号*/
DevBufferSerialNumStr=strArr[6];
}
SendInfStr="001,"+DevRecFramesStr; /*向设备发此数据表示已收到信息,否则设备会连续发三次*/
SendInfToDiv(s,SendInfStr,RemoteHostIP,RemotePort);
String SysNowTime=GetSysDT(); /*取系统时间*/
if(DevBufferDatetimeStr.substring(0,16).compareTo(SysNowTime.substring(0,16))!=0){
SendInfStr="003,"+DevBufferMachinStr+","+SysNowTime; /*设备时钟与系统不符,更新设备时间*/
SendInfToDiv(s,SendInfStr,RemoteHostIP,RemotePort);
}
break;
case "150": /*接收到实时考勤门禁机刷卡数据*/
DevRecFramesStr = strArr[1]; /*包序列号 */
DevBufferIpAddrStr = strArr[2]; /*终端IP */
DevBufferRemoteAddrStr = strArr[3]; /*远程电脑指机IP*/
DevBufferMachinStr = strArr[4]; /*机号*/
DevBufferCardidStr= strArr[5]; /*卡号*/
DevBufferReaderStr= strArr[6]; /*读头号*/
DevBufferDoorNoStr= strArr[7]; /*门或继电器号*/
DevBufferDelayStr= strArr[8]; /*门磁未关秒数,0表示已关*/
DevBufferPasswPropStr= strArr[9]; /*密码属性(0密码无效,1刷卡后按密码,2补签密码,3开门密码,4防迫胁密码)*/
DevBufferPassWStr= strArr[10]; /*密码(最多8位数字)*/
DevBufferUseTimeStr= strArr[11]; /*刷卡时间*/
if(strArr.length>12){ /*2018年以后的设备有唯一硬件序号*/
DevBufferSerialNumStr=strArr[12];
}
SendInfStr="001,"+DevRecFramesStr; /*向设备发此数据表示已收到信息,否则设备会连续发三次*/
SendInfToDiv(s,SendInfStr,RemoteHostIP,RemotePort);
/*用050指令返回开门成功,051指令返回开门失败,正式系统开发时要有重发机制 */
/*SendInfStr="051," + DevBufferMachinStr + "," + DevBufferCardidStr+ ",卡号:"+DevBufferCardidStr+"\\n姓名:张三丰 \\n状态:状态:无效卡\\n,20,1,3" */
SendInfStr="050," + DevBufferMachinStr + "," + DevBufferCardidStr+ ",卡号:"+DevBufferCardidStr+"\\n姓名:张三丰 \\n状态:欢迎关临\\n,20,1,0," + DevBufferReaderStr + "," + DevBufferDoorNoStr + ",5,20" ;
SendInfToDiv(s,SendInfStr,RemoteHostIP,RemotePort);
default: //更多的指令说明请参看通讯协议说明
}
}
s.close(); /**5、关闭资源*/
}
/*---------------------------------------------------------------------------------------------------------电脑向设备回复信息*/
static void SendInfToDiv(DatagramSocket s,String Sendinf,String RemoIp,int RemoPro) throws Exception{
//DatagramSocket s1 = new DatagramSocket(0); /** 1、建立udp socket端点 */
byte[] SendBuf = Sendinf.getBytes("gb2312"); /** 2、提供发送数据,封装打包 */
DatagramPacket dp1 = new DatagramPacket(SendBuf, SendBuf.length, InetAddress.getByName(RemoIp), RemoPro);
try {
s.send(dp1);
System.out.println("SendTo ip::"+RemoIp+"\nport::"+String.valueOf(RemoPro)+"\ndata::"+Sendinf+"\n\n");
} catch (IOException e) {
System.out.println("发送失败: ");
e.printStackTrace();
}
//s1.close();
}
/*---------------------------------------------------------------------------------------------------------判断字符串是不是一个日期时间格式*/
static boolean IsDateTime(String inputstr) {
Date date=null;
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
date=formatter.parse(inputstr);
return true;
}catch (Exception e) {
return false;
}
}
/*--------------------------------------------------------------------------------------------------------------------取电脑系统日期时间*/
static String GetSysDT() {
Date date=new Date();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String TimeStr=formatter.format(date);
return TimeStr;
}
/*----------------------------------------------------------------------------------------------------------------------------取电脑IP*/
public static String getIP() {
Enumeration<NetworkInterface> netInterfaces;
ArrayList<String> IpAddList = new ArrayList<String>();
try {
netInterfaces = NetworkInterface.getNetworkInterfaces(); // 拿到所有网卡
InetAddress ip;
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
IpAddList.add(ip.getHostAddress());
System.out.println((IpAddList.size() - 1) + "" + " " + ni.getName() + " " + ip.getHostAddress());
}
}
}
} catch (Exception e) {
}
if (IpAddList.isEmpty()) {
return "127.0.0.1";
} else {
return IpAddList.get(1); //如有多张网卡,请选择与设备相连的网卡,否则无法与设备正常通讯
}
}
}