服务器端:
package udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServer {
public static void main(String[] args) {
// TODO Auto-generated method
stub
try {
DatagramSocket
ds=new DatagramSocket(10000);
//构造DatagramPacket,接受长度为length的数据包
byte[] bt=new
byte[1000];
DatagramPacket
dp=new DatagramPacket(bt,1000);
try {
ds.receive(dp);
} catch
(IOException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(new
String(bt,0,dp.getLength()));
String
str="Welcome,i am server..";
//DatagramPacket此类表示数据报包。
dp.getAddress()得到接收到的DatagramPacket的主机的地址 DatagramPacket
dp2=new
DatagramPacket(str.getBytes(),str.length(),dp.getAddress(),dp.getPort());
try {
ds.send(dp2);
} catch
(IOException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
ds.close();
}
catch (SocketException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
2 客户端:
package udp;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClient {
public static void main(String[] args) throws
Exception {
// TODO Auto-generated method
stub
DatagramSocket ds=new
DatagramSocket();
String str="i am client";
DatagramPacket dp=new
DatagramPacket(str.getBytes(),str.length(),InetAddress.getByName("localhost"),10000);
ds.send(dp);
byte[] bt=new byte[1000];
DatagramPacket dp2=new
DatagramPacket(bt,100);
ds.receive(dp2);
System.out.println(new
String(bt,0,dp2.getLength()));
ds.close();
}
}
先运行服务器端,后运行客户端...
这个程序主要阐述udp的工作机理,简单概括如下:
服务器端:
创建套接字;调用bind()绑定服务器地址在套接字;调用recvform()无限循环等待客户进程;sendto()处理客户进程;close()撤销套接字
客户端:创建套接字;发送请求;接受请求;close()套接字