package baowen;
|
|
import tools.GetNowTime;
|
import tools.Tools;
|
|
import java.io.IOException;
|
import java.net.*;
|
|
public class Dell_udpReceive implements Runnable{
|
|
int port=7000;
|
static DatagramSocket socket;
|
static int bytlenth=1024;
|
static DatagramPacket packet;
|
static boolean startFlag=false;
|
private static Thread receiveThread;
|
|
public Dell_udpReceive(int port1){
|
try {
|
startFlag=true;
|
port=port1;
|
socket = new DatagramSocket(port);
|
byte[] data = new byte[bytlenth]; // 创建byte数组
|
packet= new DatagramPacket(data,bytlenth);
|
} catch (SocketException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
|
/**启动线程的方法*/
|
public void startThread() {
|
receiveThread = new Thread(this);
|
receiveThread.start();
|
}
|
|
@Override
|
public void run() {
|
while(startFlag) {
|
getdata();
|
}
|
}
|
|
public void getdata() {
|
if (socket != null) {
|
try {
|
socket.receive(packet); // 接收数据包
|
delludp_receive(packet);
|
} catch (IOException e) {
|
throw new RuntimeException(e);
|
}
|
}
|
}
|
|
public static void delludp_receive(DatagramPacket packet) {
|
int lenth=packet.getLength();
|
byte[] byt=subBytes(packet.getData(),0, lenth);
|
String ip=packet.getAddress().getHostAddress();//获取发送端的IP地址对象
|
int port=packet.getPort();
|
String datas = Tools.Bytes2HexString(byt);//串口来的数据
|
Dell_Baowen.intsert(ip, datas, GetNowTime.timestamp2(), port);
|
}
|
|
public static byte[] subBytes(byte[] src, int begin, int count) {
|
byte[] bs = new byte[count];
|
System.arraycopy(src, begin, bs, 0, count);
|
return bs;
|
}
|
|
|
/**将数据发给基站*/
|
public static void sendData(byte[] data,String ip2,int port2) {
|
if(socket==null) {
|
return;
|
}
|
String datas1=Tools.Bytes2HexString(data);
|
DatagramPacket packet=null;
|
InetAddress address=null;
|
//如果数据类型相同
|
try {
|
address=InetAddress.getByName(ip2);
|
} catch (UnknownHostException e) {
|
e.printStackTrace();
|
}
|
packet=new DatagramPacket(data, data.length, address, port2);
|
try {
|
socket.send(packet);
|
String datas=Tools.Bytes2HexString(data).substring(0, packet.getLength()*2);
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
|
|
|
/** 停止线程并释放资源 */
|
public static void stop() {
|
|
if (receiveThread != null && receiveThread.isAlive()) {
|
try {
|
receiveThread.join(); // 等待线程结束
|
} catch (InterruptedException e) {
|
Thread.currentThread().interrupt();
|
}
|
}
|
}
|
|
public static void stopThread() {
|
startFlag = false;//停止数据接收
|
if (socket != null && !socket.isClosed()) {
|
socket.close();//关闭socket对象
|
}
|
stop();
|
}
|
}
|