Java Socket例程3 UDP
UdpSend.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UdpSend {
public static void main(String args[]){
DatagramSocket ds = null;
DatagramPacket dp = null;
try{
ds = new DatagramSocket(3000); //实例化一个UDP的套接字并绑定3000绑定
}catch(SocketException e){
}
String str = "hello world";
try{
dp = new DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),9000);
}
catch(UnknownHostException ex1){
}
try{
ds.send(dp); //发送数据到本机的9000
}catch(IOException e){
}
ds.close();
}
}
UdpReceive.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceive {
public static void main(String args[]){
DatagramSocket ds = null; //创建一个套接字对象
byte[] buf = new byte[1024]; //实例化一个数组
DatagramPacket dp = null; //创建一个套接字结构对象
try{
ds = new DatagramSocket(9000);//实例化并绑定端口
}
catch(IOException e){
}
dp = new DatagramPacket(buf,1024);
try{
ds.receive(dp);//接收数据并存放在dp中
}
catch(IOException e2){
}
String str = new String(dp.getData(),0,dp.getLength()) +" from " +dp.getAddress().getHostAddress()+":"+dp.getPort();
System.out.println(str); //打印接收到的内容
ds.close();
}
}