java udp傳送資料
阿新 • • 發佈:2018-12-26
private final static int PORT = 8888;
private static final String HOSTNAME = "13.196.25.157";
public static void send(String data){
try (DatagramSocket socket = new DatagramSocket(0)) {
socket.setSoTimeout(10000);
InetAddress host = InetAddress.getByName(HOSTNAME);
byte [] buf = toBytes(data);
DatagramPacket packet = new DatagramPacket(buf, buf.length,host, PORT);
socket.send(packet);
socket.close();
System.out.println("send alreay");
} catch (IOException e) {
System.out.println("error:{}" +e);
}
}
public static byte[] toBytes(String str) {//字串轉為16進位制byte陣列
if(str == null || str.trim().equals("")) {
return new byte[0];
}
byte[] bytes = new byte[str.length() / 2];
for(int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2 , i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}
return bytes;
}