Socket簡單入門UDP協議(1)
阿新 • • 發佈:2018-11-08
一、伺服器端程式碼:
1 import java.io.IOException; 2 import java.net.DatagramPacket; 3 import java.net.DatagramSocket; 4 import java.net.SocketAddress; 5 import java.net.SocketException; 6 7 8 /** 9 * 伺服器端 10 * */ 11 public class AskServer { 12 public static void main(String[] args) { 13 try{ 14 //1.建立接受方(伺服器)套接字,並繫結埠號 15 DatagramSocket ds=new DatagramSocket(8800); 16 //2.確定資料包接受的資料的陣列大小 17 byte[] buf=new byte[1024]; 18 //3.建立接受型別的資料包,資料將儲存在陣列中 19 DatagramPacket dp=new DatagramPacket(buf, buf.length); 20 //4.通過套接字接受資料21 ds.receive(dp); 22 //5.解析傳送方傳送的資料 23 String mess=new String(buf,0,dp.getLength()); 24 System.out.println("客戶端說:"+mess); 25 //響應客戶端 26 String reply="您好,我在的,請諮詢!"; 27 byte[] replys=reply.getBytes(); 28 //響應地址 29SocketAddress sa=dp.getSocketAddress(); 30 //資料包 31 DatagramPacket dp2=new DatagramPacket(replys, replys.length,sa); 32 //傳送 33 ds.send(dp2); 34 //6.釋放資源 35 ds.close(); 36 } catch (SocketException e) { 37 // TODO Auto-generated catch block 38 e.printStackTrace(); 39 } catch (IOException e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 44 } 45 }
二、客戶端程式碼:
1 import java.io.IOException; 2 import java.net.DatagramPacket; 3 import java.net.DatagramSocket; 4 import java.net.InetAddress; 5 import java.net.SocketException; 6 import java.net.UnknownHostException; 7 8 /** 9 * 客戶端 10 * */ 11 public class AskClient { 12 public static void main(String[] args) { 13 //1.確定傳送給伺服器的資訊、伺服器地址以及埠 14 String mess="你好,我想諮詢一個問題!"; 15 byte[] buf=mess.getBytes(); 16 InetAddress ia=null; 17 try { 18 ia=InetAddress.getByName("localhost"); 19 } catch (UnknownHostException e) { 20 e.printStackTrace(); 21 } 22 int port=8800; 23 //2.建立資料包,傳送指定長度的資訊到指定伺服器的指定埠 24 DatagramPacket dp=new DatagramPacket(buf, buf.length,ia,port); 25 //3.建立DatagramSocket物件 26 DatagramSocket ds=null; 27 try { 28 ds=new DatagramSocket(); 29 } catch (SocketException e) { 30 e.printStackTrace(); 31 } 32 //4.向伺服器傳送資料包 33 try { 34 ds.send(dp); 35 } catch (IOException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 40 //接受伺服器的響應並列印 41 byte[] buf2=new byte[1024]; 42 //建立接受型別的資料包,資料將儲存在陣列中 43 DatagramPacket dp2=new DatagramPacket(buf2, buf2.length); 44 //通過套接字接受資料 45 try { 46 ds.receive(dp2); 47 } catch (IOException e) { 48 e.printStackTrace(); 49 } 50 //解析伺服器的響應 51 String reply=new String(buf2,0,dp2.getLength()); 52 System.out.println("伺服器的響應為:"+reply); 53 54 //5.釋放資源 55 ds.close(); 56 } 57 }