TCP和UDP最大的區(qū)別在于是否需要客戶端與服務(wù)端建立連接后才能進(jìn)行 數(shù)據(jù)傳輸,TCP的,傳輸前先開服務(wù)端兵睛,accept,等客戶端接入窥浪,然后獲得 客戶端socket然后進(jìn)行IO操作,而UDP則不用笛丙,UDP以數(shù)據(jù)報(bào)作為數(shù)據(jù)的傳輸載體漾脂,在進(jìn)行傳輸時(shí) 首先要把傳輸?shù)臄?shù)據(jù)定義成數(shù)據(jù)報(bào)(Datagram),在數(shù)據(jù)報(bào)中指明數(shù)據(jù)要到達(dá)的Socket(主機(jī)地址 和端口號(hào))胚鸯,然后再將數(shù)據(jù)以數(shù)據(jù)報(bào)的形式發(fā)送出去骨稿,然后就沒有然后了,服務(wù)端收不收到我就 不知道了姜钳,除非服務(wù)端收到后又給我回一段確認(rèn)的數(shù)據(jù)報(bào)~
?
1.服務(wù)端實(shí)現(xiàn)步驟:
Step 1:創(chuàng)建DatagramSocket坦冠,指定端口號(hào)
Step 2:創(chuàng)建DatagramPacket
Step 3:接收客戶端發(fā)送的數(shù)據(jù)信息
Step 4:讀取數(shù)據(jù)
示例代碼:
public class UPDServer { public static void main(String[] args) throws IOException { /* * 接收客戶端發(fā)送的數(shù)據(jù) */ // 1.創(chuàng)建服務(wù)器端DatagramSocket,指定端口 DatagramSocket socket = new DatagramSocket(12345); // 2.創(chuàng)建數(shù)據(jù)報(bào)哥桥,用于接收客戶端發(fā)送的數(shù)據(jù) byte[] data = new byte[1024];// 創(chuàng)建字節(jié)數(shù)組辙浑,指定接收的數(shù)據(jù)包的大小 DatagramPacket packet = new DatagramPacket(data, data.length); // 3.接收客戶端發(fā)送的數(shù)據(jù) System.out.println("****服務(wù)器端已經(jīng)啟動(dòng),等待客戶端發(fā)送數(shù)據(jù)"); socket.receive(packet);// 此方法在接收到數(shù)據(jù)報(bào)之前會(huì)一直阻塞 // 4.讀取數(shù)據(jù) String info = new String(data, 0, packet.getLength()); System.out.println("我是服務(wù)器拟糕,客戶端說:" + info); /* * 向客戶端響應(yīng)數(shù)據(jù) */ // 1.定義客戶端的地址判呕、端口號(hào)、數(shù)據(jù) InetAddress address = packet.getAddress(); int port = packet.getPort(); byte[] data2 = "歡迎您!".getBytes(); // 2.創(chuàng)建數(shù)據(jù)報(bào)送滞,包含響應(yīng)的數(shù)據(jù)信息 DatagramPacket packet2 = new DatagramPacket(data2, data2.length, address, port); // 3.響應(yīng)客戶端 socket.send(packet2); // 4.關(guān)閉資源 socket.close(); } }
2.客戶端實(shí)現(xiàn)步驟:
Step 1:定義發(fā)送信息
Step 2:創(chuàng)建DatagramPacket侠草,包含將要發(fā)送的信息
Step 3:創(chuàng)建DatagramSocket
Step 4:發(fā)送數(shù)據(jù)
public class UDPClient { public static void main(String[] args) throws IOException { /* * 向服務(wù)器端發(fā)送數(shù)據(jù) */ // 1.定義服務(wù)器的地址、端口號(hào)犁嗅、數(shù)據(jù) InetAddress address = InetAddress.getByName("localhost"); int port = 8800; byte[] data = "用戶名:admin;密碼:123".getBytes(); // 2.創(chuàng)建數(shù)據(jù)報(bào)边涕,包含發(fā)送的數(shù)據(jù)信息 DatagramPacket packet = new DatagramPacket(data, data.length, address, port); // 3.創(chuàng)建DatagramSocket對(duì)象 DatagramSocket socket = new DatagramSocket(); // 4.向服務(wù)器端發(fā)送數(shù)據(jù)報(bào) socket.send(packet); /* * 接收服務(wù)器端響應(yīng)的數(shù)據(jù) */ // 1.創(chuàng)建數(shù)據(jù)報(bào),用于接收服務(wù)器端響應(yīng)的數(shù)據(jù) byte[] data2 = new byte[1024]; DatagramPacket packet2 = new DatagramPacket(data2, data2.length); // 2.接收服務(wù)器響應(yīng)的數(shù)據(jù) socket.receive(packet2); // 3.讀取數(shù)據(jù) String reply = new String(data2, 0, packet2.getLength()); System.out.println("我是客戶端褂微,服務(wù)器說:" + reply); // 4.關(guān)閉資源 socket.close(); } }