UDP:非面向连接的提供不可靠的数据包式的数据传输的协议.类似于从邮局发送信件的过程
DatagramPacket,DatagramSocket,MulticastSocket等类使用UDP协议进行网络通讯
TCP:面向连接的能够提供可靠地流式数据的传输协议,类似于打电话的过程.
URL,URLConnection,Socket,ServerSocket等类都使用TCP协议进行网络通讯.
-
TCP和UDP的建立时间
TCP有建立时间,UDP没有建立时间
UDP传输大小有限制:64K以内
TCP的应用:Telent,ftp
UDP的应用:ping
-
构造UDP的通信
DatagramSocket()
DatagramSocket(int port)
DatagramPacket(byte ibuf[],int ilength)//接收
DatagramPacket(byte ibuf[],int ilength,InetAddress iaddr,int iport)//发送
-
收数据报
DatagramPacket packet=new DatagramPacket(buf,256);
socket.receive(packet);
-
发数据报
DatagramPacket packet=new DatagramPacket(buf,buf.length,address,port);
socket.send(packet);
客户方程序:
public class QuoteClient{
public static void main(String[] args)throws IOException{
if(args.length!=1){
System.out.println("Usage:java QuoteClient<hostname>");
return;
}
DatagramSocket socket=new DatagramSocket();
//send request
byte[]buf=new byte[256];
InetAddress address=InetAddress.getByName(args[0]);
DatagramPacket packet=new DatagramPacket(buf,buf.length,address,4445);
Socket.send(Packet);
//get response
packet=new DatagramPacket(buf,buf.length);
socket.receive(packet);
//display responese
String received=new String(packet.getData());
System.out.println("Quote of the Moment:"+received);
socket.close();
}
}
服务器程序:
public class QuoteServer {
public static void main(String[] args) throws java.io.IOException {
new QuoteServerThread().start();
}
}
程序QuoteServerThread
public class QuoteServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
public QuoteServerThread() throws IOException {
this("QuoteServerThread");
}
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
try {
in = new BufferedReader(new FileReader("one-liners.txt"));
} catch (FileNotFoundException e) {
System.err.println("Could not open quote file.Serving time instead");
}
}
public void run (){
while (moreQuotes){
try {
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String dString=null;
if (in==null)
dString=new Date().toString();
else dString=getNextQuote();
buf = dString.getBytes();
//发送响应客户端的地址和端口号
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
}catch (IOException e){
e.printStackTrace();
moreQuotes=false;
}
}
socket.close();
}
protected String getNextQuote(){
String returnValue=null;
try{
if((returnValue=in.readLine())==null){
in.close();
moreQuotes=false;
returnValue="No more quotes.Goodbye.";
}
}catch(IOException e){
returnValue="IOException occurred in server";
}
return returnValue;
}
}
}