Java 基礎 (網路程式設計)
阿新 • • 發佈:2021-11-29
Java 是 Internet上的語言,它從語言級上提供了對網路應用程式的支援,程式設計師能夠很容易開發常見的網路應用程式。
Java 提供的網路類庫,可以實現無痛的網路連線,聯網的底層細節被隱藏在 Java 的本機安裝系統裡,由 JVM 進行控制。並且 Java 實現了一個跨平臺的網路庫,程式設計師面對的是一個統一的網路程式設計環境。
實現網路中的主機互相通訊
1.通訊雙方地址
IP
埠號
2.一定的規則 (即:網路通訊協議。有兩套參考模型)
OSI 參考模型: 模型過於理想化,未能在因特網上進行廣泛推廣
TCP/IP 參考模型(或TCP/IP協議): 事實上的國際標準。
網路通訊協議
埠分類
公認埠: 0~1023。被預先定義的服務通訊佔用(如:HTTP佔用埠80,FTP佔用埠21,Telnet佔用埠23)
註冊埠: 1024~49151。分配給使用者程序或應用程式。(如:Tomcat佔用埠8080,MySQL佔用埠3306,Oracle佔用埠1521等)。
動態/私有埠:49152~65535。
埠號與IP地址的組合得出一個網路套接字:Socket。
TCP 和 UDP
TCP協議 > 使用TCP協議前,須先建立TCP連線,形成傳輸資料通道 > 傳輸前,採用“三次握手”方式,點對點通訊,是可靠的 > TCP協議進行通訊的兩個應用程序:客戶端、服務端。 > 在連線中可進行大資料量的傳輸> 傳輸完畢,需釋放已建立的連線,效率低 UDP協議 > 將資料、源、目的封裝成資料包,不需要建立連線 > 每個資料報的大小限制在64K內 > 傳送不管對方是否準備好,接收方收到也不確認,故是不可靠的 > 可以廣播發送 > 傳送資料結束時無需釋放資源,開銷小,速度快
TCP
TCPTest1.java
package com.klvchen.java1; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; public class TCPTest1 { //客戶端 @Test public void client(){ Socket socket = null; OutputStream os = null; try { //1.建立Socket物件,指明伺服器端的ip和埠號 InetAddress inet = InetAddress.getByName("127.0.0.1"); socket = new Socket(inet, 8899); //2.獲取一個輸出流,用於輸出資料 os = socket.getOutputStream(); //3. 寫出資料的操作 os.write("你好,我是客戶端mm".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //4.資源的關閉 if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } //伺服器 @Test public void server(){ ServerSocket ss = null; Socket socket = null; InputStream is = null; ByteArrayOutputStream baos = null; try { //1.建立伺服器端的ServerSocket,指明自己的埠號 ss = new ServerSocket(8899); //2.呼叫accept()表示接收來自於客戶端的socket socket = ss.accept(); //3.獲取輸入流 is = socket.getInputStream(); // 不建議這樣寫,可能會有亂碼 //byte[] buffer = new byte[20]; //int len; //while ((len = is.read(buffer)) != -1) { // String str = new String(buffer, 0, len); // System.out.println(str); //} //4.讀取輸入流中的資料 baos = new ByteArrayOutputStream(); byte[] buffer = new byte[5]; int len; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0 , len); } System.out.println(baos.toString()); System.out.println("收到來自於:" + socket.getInetAddress().getHostAddress() + "的資料"); } catch (IOException e) { e.printStackTrace(); } finally { //5.關閉資源 if (baos != null) { try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (ss != null) { try { ss.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
TCPTest2.java
package com.klvchen.java1; import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /* 客戶端傳送檔案給服務端,服務端將檔案儲存在本地 */ public class TCPTest2 { @Test public void client() throws IOException { Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090); OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream(new File("1.png")); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } fis.close(); os.close(); socket.close(); } @Test public void server() throws IOException{ ServerSocket ss = new ServerSocket(9090); Socket socket = ss.accept(); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("4.png")); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } fos.close(); is.close(); socket.close(); ss.close(); } }
TCPTest3.java
package com.klvchen.java1; import org.junit.Test; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /* 從客戶端傳送檔案給服務端,服務端儲存到本地。並返回“傳送成功”給客戶端。 */ public class TCPTest3 { @Test public void client() throws IOException { Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090); OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream(new File("1.png")); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } socket.shutdownOutput(); //接收來自於伺服器端的資料,並顯示到控制檯上 InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] bufferr = new byte[1024]; int len1; while ((len1 = is.read(bufferr)) != -1) { baos.write(bufferr,0,len1); } System.out.println(baos.toString()); fis.close(); os.close(); socket.close(); baos.close(); is.close(); } @Test public void server() throws IOException{ ServerSocket ss = new ServerSocket(9090); Socket socket = ss.accept(); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("4.png")); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } OutputStream os = socket.getOutputStream(); os.write("你好,美女,照片我已收到,非常漂亮!".getBytes()); fos.close(); is.close(); socket.close(); ss.close(); os.close(); } }
UDP
UDPTest.java
package com.klvchen.java1; import org.junit.Test; import java.io.IOException; import java.net.*; public class UDPTest { @Test public void sender() throws IOException { DatagramSocket socket = new DatagramSocket(); String str = "我是UDP方式傳送的導彈"; byte[] data = str.getBytes(); InetAddress inet = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(data, 0, data.length,inet,9090); socket.send(packet); socket.close(); } @Test public void receiver() throws IOException{ DatagramSocket socket = new DatagramSocket(9090); byte[] buffer = new byte[100]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); socket.receive(packet); System.out.println(new String(packet.getData(), 0, packet.getLength())); socket.close(); } }
URL
* URL(Uniform Resource Locator): 統一資源定位符,它表示 Internet 上某一資源的地址。 * 它是一種具體的URI,即URL可以用來標識一個資源,而且還指明瞭如何locate這個資源。 * 通過URL我們可以訪問 Internet上的各種網路資源,比如最常見的 www,ftp站點。瀏覽器通過解析給定的URL可以在網路上查詢相應的檔案或其他資源。 * URL的基本結構由5部分組成: <傳輸協議>://<主機名>:<埠號>/<檔名>#片段名?引數列表 例如: http://192.168.1.100:8080/helloworld/index.jsp#a?username=shkstart&password=123
URLTest.java
package com.klvchen.java1; import java.net.MalformedURLException; import java.net.URL; public class URLTest { public static void main(String[] args){ URL url = null; try { url = new URL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201810%2F05%2F20181005142528_yinka.jpg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1638864631&t=26377d1d4652702f21909f93fee1af0e"); // 獲取URL的協議名稱 System.out.println(url.getProtocol()); // 獲取該URL的主機名 System.out.println(url.getHost()); // 獲取該URL的埠號 System.out.println(url.getPort()); //獲取該URL的檔案路徑 System.out.println(url.getPath()); //獲取該URL的檔名 System.out.println(url.getFile()); // 獲取該URL的查詢名 System.out.println(url.getQuery()); } catch (MalformedURLException e) { e.printStackTrace(); } } }
URLTest1.java
package com.klvchen.java1; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class URLTest1 { public static void main(String[] args){ HttpURLConnection urlConnection = null; InputStream is = null; FileOutputStream fos = null; try { URL url = new URL("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201810%2F05%2F20181005142528_yinka.jpg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1638864631&t=26377d1d4652702f21909f93fee1af0e"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.connect(); is = urlConnection.getInputStream(); fos = new FileOutputStream("day10\\5.jpeg"); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } System.out.println("下載完成"); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (urlConnection != null) { urlConnection.disconnect(); } } } }