package cn.com.sany.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* 工具类, 主动和被动发送消息所需要用到的公共方法
* 避免维护重复的代码
*
*
*/
public class UDPTool {
/**
* 得到当前的时间
*
* @return
*/
public static String getCurrentTime() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss ");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String str = formatter.format(curDate);
return str;
}
public static String toHexString(byte[] bufIn, int bytesLen) {
if (bytesLen == -1) {
bytesLen = bufIn.length;
}
StringBuffer buff = new StringBuffer();
for (int i = 0; i < bytesLen; i++) {
buff.append(Integer.toHexString((bufIn[i]) & 0xFF) + " ");
}
return buff.toString();
}
/**
* 发送数据包
*
*/
public static void sendData(String ip, int port, byte[] data, DatagramSocket socket) {
try {
System.out.println("数据发送!");
DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(ip), port);
socket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 接收数据帧, 在发送端口上面进行接收
*/
public static void receiveData(DatagramSocket socket)
{
try {
byte[] buffer = new byte[65508];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
System.out.println("---接收数据--");
socket.receive(packet);
byte[] data = packet.getData();
int len = packet.getLength();
String hexString = UDPTool.toHexString(data, len);
String time = UDPTool.getCurrentTime();
System.out.println("---接收到服务端的时间和数据(16)--" + time + "内容:" + hexString);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 1
- 2
前往页