⑴ 請教大神,怎麼使用java實現UDP埠掃描
給你個UDP服務端與客戶端的示例:
服務端代碼:
importjava.net.DatagramPacket;
importjava.net.InetAddress;
importjava.net.MulticastSocket;
publicclassUDPMulticastServer{
finalstaticintRECEIVE_LENGTH=1024;
staticStringmulticastHost="224.0.0.1";
staticintlocalPort=9998;
publicstaticvoidmain(String[]args)throwsException{
InetAddressreceiveAddress=InetAddress.getByName(multicastHost);
if(!receiveAddress.isMulticastAddress()){//測試是否為多播地址
thrownewException("請使用多播地址");
}
intport=localPort;
=newMulticastSocket(port);
receiveMulticast.joinGroup(receiveAddress);
booleanisStop=false;
while(!isStop){
DatagramPacketdp=newDatagramPacket(newbyte[RECEIVE_LENGTH],RECEIVE_LENGTH);
receiveMulticast.receive(dp);
Stringdata=newString(dp.getData()).trim();
System.out.println(data);
if("exit".equals(data)){
System.out.println("程序退出");
isStop=true;
}
}
receiveMulticast.close();
}
}
客戶端代碼:
importjava.net.DatagramPacket;
importjava.net.InetAddress;
importjava.net.MulticastSocket;
publicclassUDPMulticastClient{
staticStringdestAddressStr="224.0.0.1";
staticintdestPortInt=9998;
staticintTTLTime=4;
publicstaticvoidmain(String[]args)throwsException{ InetAddressdestAddress=InetAddress.getByName(destAddressStr);
if(!destAddress.isMulticastAddress()){//檢測該地址是否是多播地址
thrownewException("地址不是多播地址");
}
intdestPort=destPortInt;
MulticastSocketmultiSocket=newMulticastSocket();
// intTTL=TTLTime;
// multiSocket.setTimeToLive(TTL);
byte[]sendMSG="exit".getBytes();
DatagramPacketdp=newDatagramPacket(sendMSG,sendMSG.length,destAddress,destPort);
multiSocket.send(dp);
multiSocket.close();
}
}
⑵ java怎麼實現JSON打包UDP
java實現JSON打包UDP cJSON支持在C程序中創建和解析JSON數據,其提供多種方法供C程序使用,最直接的是將cJSON.c和cJSON.h加入到C工程中
(1) QJsonObject用於在Qt中創建JSON對象
(2)數據傳輸通過UDP運行