UDP傳輸案例
阿新 • • 發佈:2017-05-12
nts sender oca auto bytes ktr exception sleep true
1 /** 2 * 發送方 3 */ 4 public class DataGramSender { 5 6 public static void main(String[] args) { 7 try { 8 //9999向外發的端口號 9 DatagramSocket socket = new DatagramSocket(9999); 10 int i=1; 11 while(true){ 12 String content="Tom"+i;13 byte[] buf=content.getBytes(); 14 //創建數據報表 15 DatagramPacket packet = new DatagramPacket(buf, buf.length); 16 //設置包要發送的地址和端口號 17 packet.setAddress(InetAddress.getByName("localhost")); 18 packet.setPort(8888);19 socket.send(packet); 20 System.out.println("sent"+content); 21 Thread.sleep(1000); 22 i++; 23 } 24 } catch (Exception e) { 25 // TODO Auto-generated catch block 26 e.printStackTrace(); 27 }28 } 29 } 30 31 32 /** 33 * 接收方 34 * 35 */ 36 public class DataGramRece { 37 public static void main(String[] args) { 38 try { 39 //創建數據報套接字 40 DatagramSocket socket = new DatagramSocket(8888); 41 byte[] buf=new byte[1024*64]; 42 DatagramPacket packet = new DatagramPacket(buf, buf.length); 43 while(true){ 44 socket.receive(packet); 45 //得到收到的數據長度 46 int len=packet.getLength(); 47 System.out.println(new String(buf,0,len)); 48 } 49 } catch (Exception e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } 53 } 54 }
UDP傳輸案例