UDP 客户端
UDP 服务器端代码
public class Udpsend {
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket();
String str = "hello";
DatagramPacket dp = new DatagramPacket(str.getBytes(), str
.getBytes().length, InetAddress
.getByName("192.168.1.103"), 4001);
ds.send(dp);
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
UDP 服务器端代码
public class UdpRecv {
private static DatagramPacket packet;
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket(4001);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ds.receive(packet);
String strRecv = new String(packet.getData(), 0, packet.getLength())
+ " from "
+ packet.getAddress().getHostAddress()
+ ":"
+ packet.getPort();
System.out.println(strRecv);
ds.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}