網路程式設計基礎
阿新 • • 發佈:2021-06-19
-
如何定位網路上的一臺或多臺主機,定位主機上的應用(寫給人的地址)
-
如何進行可靠高效進行資料傳輸(需要貼什麼郵票)
解決問題一:IP和埠號
IP和埠
IP地址
1.唯一標識Internet上的計算機(通訊實體)
2.在Java中使用InetAddress類代表IP
3.分類方式1:IPV4和IPV6
分類方式2:全球資訊網 和 區域網
4.域名:代替IP,方便記憶 例如:www.baidu.com
5.本地迴路地址:120.0.0.1 對應:localhost
6.如何例項化:兩種 getByName(String host) getLocalHost()
兩個常用方法:getHostName() 獲取域名
getHostAddress() 獲取地址IP
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) {
try {
InetAddress byName = InetAddress.getByName("www.baidu.com");
System.out.println(byName.toString());
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost);
System.out.println(byName.getHostName());
System.out.println(byName.getHostAddress());
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
埠號
1.標識正在計算機上執行的程序(程式)
2.不同程序要有不同的埠號
3.範圍: 16位的整數 0-65535
埠號和IP地址的組合得出一個網路套接字:Socket
協議
TCP協議
三次握手(建立,確保兩個人都在 客戶端向伺服器發訊息問在不在,伺服器回訊息在,客戶端回覆)
四次揮手(釋放,兩個人都先對方發了訊息說要斷開,各自再回一條資訊,客戶端先,伺服器發的時候,客戶端回訊息只是印證伺服器也沒有關閉)
可靠,
需要釋放連線,效率低
UDP協議
將資料,源,目的封裝在資料包
不可靠
速度快,無需釋放資源,開銷小
TCP
//客戶端