先說一下關於InetAddress類,用一個小例子:
import java.net.InetAddress; import java.net.UnknownHostException; public class IPDemo { public static void main(String[] args) throws UnknownHostException { // InetAddress i = InetAddress.getLocalHost();獲取本地信息 // System.out.println(i); InetAddress i = InetAddress.getByName("www.baidu.com"); System.out.println(i.getHostAddress()); System.out.println(i.getHostName()); } }
UDP是一種面向無連接的傳輸方式,傳輸速度快,但是每次傳輸的大小不能超過64K
怎樣來編寫UDP?
發送數據步驟:
1.創建socket服務
2.創建數據包
3.將數據封裝到數據包中,添加ip和端口以及數據
4.發送
5.關閉資源
接收數據步驟:
1.創建socket服務,並監聽端口
2.創建數據包,用來接收數據
3.用socket接收數據到數據包中
4.從數據包中取出數據
5.關閉資源
下面用代碼演示:
import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; class UdpSend{ //1.創建socket服務 //2.傳輸數據,並打包 //3.發送 //4.關閉資源 public static void main(String[] args) throws Exception { //1.創建socket服務 DatagramSocket socket = new DatagramSocket(10000);//指定發送器端口 //2.傳輸數據,並打包 byte[] buf = "udp hello".getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, InetAddress.getByName("localhost"), 8888);//指定應用程序端口 //發送 socket.send(packet); //關閉資源 socket.close(); System.out.println("over"); } } /* * 1.創建服務socket,並監聽端口 * 2.定義一個數據包,用來接受數據包 * 3.用socket服務接受的數據保存到,數據包中 * 4.取出數據 * 5.關閉資源 */ class UdpRece{ public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket(8888);//指定應用程序的端口 byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); String data = new String(dp.getData(),0,dp.getLength()); System.out.println(ip+":"+port+":"+data); ds.close(); } } public class UdpDemo { public static void main(String[] args) { } }
上面傳送一次數據,下面寫一個增強版的。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; class Send{ public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String line =null; while((line = reader.readLine())!=null){ if("886".equals(line)){ break; } byte[] buf = line.getBytes(); DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),8888); socket.send(dp); } reader.close(); socket.close(); } } class Rece{ @SuppressWarnings("resource") public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(8888); while(true){ byte[] buf = new byte[1024]; DatagramPacket dp =new DatagramPacket(buf, buf.length); socket.receive(dp); String data = new String(dp.getData(),0,dp.getLength()); String ip = dp.getAddress().getHostAddress(); int port = dp.getPort(); System.out.println(ip+":"+port+":"+data); } } } public class UdpDemo2 { public static void main(String[] args) { } }
總結:其實java中將網絡傳輸的部件,都封裝成對象,非常方便使用,在網絡編程中主要是記住步驟。