-
UDP concept:
UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETF RFC 768是UDP的正式规范。UDP在IP报文的协议号是17。(from baike)
- UDP program:
因爲UDP協議是一種無連接的協議,所以
(1)、每次發送數據並不需要綁定,只需要使用DatagramPacket()構造好對應的數據包就可以了;
(2)、沒有像TCP一樣的ServerSocket 與Socket之分,雙方都用DatagramPacket初始化;
(3)、發送接收用send(數據包),receive(數據包)
下面上代碼:
*UDP並無Server與Client之分,但是代碼一個發送一個接受就起了這名字(這並不重要~逃)
*發送成功之後雙方就建立了一個鏈接(虛),可以互發數據
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) {
DatagramSocket dgs = null;
try {
dgs=new DatagramSocket(8888);
//receive
byte[] buf=new byte[256];
int length=256;
DatagramPacket dgp=new DatagramPacket(buf, length);
dgs.receive(dgp);
System.out.println("receive from client:"+new String(buf, 0, length)); //send
String str="yeah i have receivered~";
System.out.println(dgp.getAddress());//use last time's packet to get the address
System.out.println(dgp.getPort());
DatagramPacket dgp_send=new DatagramPacket(str.getBytes(),str.length(), dgp.getAddress(), dgp.getPort());
dgs.send(dgp_send);
dgs.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
dgs.close();
}
}
}
UdpServer
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class UdpClient {
public static void main(String[] args) {
DatagramSocket dgs = null;
try {
dgs=new DatagramSocket();
//send->server
String str="so dirty haha~";
DatagramPacket dgp_send=new DatagramPacket(str.getBytes(),0,str.length(),InetAddress.getByName("localhost"),8888);
dgs.send(dgp_send);
//receive from server
byte[] buf=new byte[256];
DatagramPacket dgp2_receive=new DatagramPacket(buf, 256);
dgs.receive(dgp2_receive);
System.out.println("receive from server:"+new String(buf,0,256));
dgs.close(); } catch (Exception e) {
System.out.println("error:"+e);
}
}
}
UdpClient
p.s.I:Server 的 send 部分使用之前用來接收數據的包dgp來取得發送者的address以及port,然後再用新的DatagramPacket來發送數據
p.s.II:DatagramPacket的搆造函數中,byte[]用來放數據,length用來放長度,程序簡單所以數字亂寫的(ha