//UDPServer
ClassServerThread extends Thread {
Publicvoid run () {
Try{
//创建一个DatagramSocket对象,并制定监听端口号
DatagramSocketsocket = new DatagramSocket(4567);
Bytedata [] = new byte [1024];
//创建一个空的DatagramPacket对象
DatagramPacketpacket = new DatagramPacket (data , data.length);
//使用receive方法接受客户端所发送的数据
Socket.receive(packet);// 阻塞方法
Stringresult = new String(packet.getData() , packet.getOffset() ,packet.getLength()); // 设置数据偏移量,得到该次数据的长度
System.out.println("result-->"+ result);
}catch (Execption e) {
e.printStackTrace();
}
}
}
//UDPClient
Publicstatic void main (String [] args) {
Try{
//创建一个DatagramSocket对象,并制定监听端口号
DatagramSocketsocket = new DatagramSocket(4567);
InetAddressserverAddress = InetAddress.getByName("192.168.1.1");
Stringstr = "hello";
Bytedata [] = str.getBytes();
DatagramPacketpacket = new DatagramPacket(data , data.length , serverAddress ,4567);
Socket.send(packet);
}catch (Execption e) {
e.printStackTrace();
}
}