java udp通信
package net.kkxm.kms;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import net.kkxm.kms.datatool.formatter.DataTran;
public class TestUdp {
// 客户端
public static void send(byte[] data, String ip, int port) throws Exception {
DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
// 这里是指定发送的客户端端口,因为该协议规定只接收由此端口发出的数据
s.bind(new InetSocketAddress(9001));
DatagramPacket p = new DatagramPacket(data, 0, data.length, new InetSocketAddress(ip, port));
System.out.println("# " + DataTran.byteArrayToHexString(data));
s.send(p);
s.receive(p);
byte[] bytRecv = p.getData();
System.out.println("> " + DataTran.byteArrayToHexString(bytRecv));
s.close();
}
public static void main(String[] args) throws Exception {
String strSend = "000000240001000000011F2F000000110049894778983307FBCB5CEFDA8B1BC2615FB6B4";
byte[] bytSend = DataTran.hexStringToByteArray(strSend);
String ip = "192.168.10.26";
int port = 9396;
send(bytSend, ip, port);
}
}