b_nk_熱心的牛牛 & 三角形(思維題:二分 | 斐波那契變形)
網路程式設計
1.1 概述
計算機網路:
計算機網路是指將地理位置不同的具有獨立功能的多臺計算機及其外部裝置,通過通訊線路連線起來,在網路作業系統,網路管理軟體及網路通訊協議的管理和協調下,實現資源共享和資訊傳遞的計算機系統。
網路程式設計的目的:
無線電臺...傳播交流資訊,資料交換。通訊
預備知識:
-
如何準確定位網路上的一臺主機? IP地址:埠號 例如:192.168.16.124:埠,定位到這個計算機上的某個資源
-
找到目標主機,如何傳輸資料?
javaweb : 網頁程式設計 B/S
網路程式設計 : TCP/IP C/S
1.2 網路通訊的要素
如何實現網路的通訊?
通訊雙方的地址:
- ip
- 埠號
規則:網路通訊的協議
OSI參考模型
TCP/IP參考模型
小結:
- 網路程式設計中主要有2個問題:
- 如何準確的定位到網路上的一臺或者多臺主機
- 找到主機之後如何進行通訊
- 網路程式設計中的要素
- IP和埠號
- 網路通訊協議
1.3 IP
InetAddress
-
唯一定位一臺網路上的計算機
-
127.0.0.1:本機localhost
-
ip地址的分類
-
ipv4/ipv6
-
IPv4 : 4個位元組。0-255,42億;30億都在北美,亞洲4億。2011年就用盡;
-
IPv6 : 128位。8個無符號整數!
2001:0bb2:aaaa:0015:98yu:2131:1111:9id9
-
-
公網(網際網路)- 私網(區域網)
- ABCD類
- 192.168.xx.xx 專門給組織內部使用
-
try { //獲取本機地址 InetAddress inetAddress = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress); InetAddress inetAddress3 = InetAddress.getByName("localhost"); System.out.println(inetAddress3); InetAddress inetAddress4 = InetAddress.getLocalHost(); System.out.println(inetAddress4); //查詢網站ip地址 InetAddress inetAddress2 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress2); //常用方法 System.out.println(inetAddress2.getAddress()); System.out.println(inetAddress2.getCanonicalHostName());//規範的名字 System.out.println(inetAddress2.getHostAddress());//ip System.out.println(inetAddress2.getHostName());//域名,或者自己電腦的名字 } catch (UnknownHostException e) { e.printStackTrace(); }
1.4 埠
埠表示 計算機上的一個程式的程序;
-
不同的程序有不同的埠號!用來區分軟體!
-
被規定0-65535
-
TCP,UDP : 655535 * 2 單個協議下,埠號不能衝突
-
埠分類:
-
公有埠0 - 1023
-
HTTP : 80
-
HTTPS : 443
-
FTP: 21
-
Telent : 23
-
程式註冊埠:1024 - 49151,分配使用者或者程式
- Tomcat : 8080
- MySQL : 3306
- Oracle : 1521
-
動態、私有:49152 - 65535
netstat -ano #檢視所有的埠 netstat -ano|findstr "5900" tasklist|findstr "8696" Ctrl + Shift + ESC 工作管理員
-
```java
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
System.out.println(socketAddress);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",8080);
System.out.println(socketAddress2);
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName());//地址
System.out.println(socketAddress.getPort());//埠
1.5 通訊協議
協議:約定。
網路通訊協議 : 速率,傳輸位元速率,程式碼結構,傳輸控制....
問題:非常的複雜?——— 分層
TCP/IP一組協議
重要:
- TCP : 使用者傳輸協議
- UDP: 使用者資料包協議
- IP : 網路互連協議
TCP UDP 對比:
TCP:打電話
-
連線,穩定
-
三次握手
四次揮手
最少需要三次,保證穩定連線! A:你瞅啥? B:瞅你咋地? A:幹一場! A:我要走了。 B:我知道你要走了。 B:你真的走了嗎? A:我真的走了。
-
客戶端、服務端
-
傳輸完成、釋放連線、效率低
UDP: 發簡訊
- 不連線,不穩定
- 客戶端、伺服器:沒有明確的界限
- 不管有沒有準備好,都可以發給你
- 導彈
- DDOS:洪水攻擊!飽和攻擊
1.6 TCP
客戶端
- 連線伺服器Socket
- 傳送訊息
Socket socket = null;
OutputStream os =null;
try {
//1.我得知道伺服器的地址
InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
int port =9999;
//2.建立以一個socket連線
socket = new Socket(inetAddress,port);
//3.傳送訊息 IO流
os = socket.getOutputStream();
os.write("hello,i'm litzhi.".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
服務端
- 建立伺服器埠 ServerSocket
- 等待使用者的連線 accept
- 接收使用者的訊息
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
ByteArrayOutputStream bos=null;
try {
//1.我得有一個地址
serverSocket = new ServerSocket(9999);
while (true) {
//2.等待客戶端連線過來
socket = serverSocket.accept();
//3.讀取客戶端的訊息
is = socket.getInputStream();
//管道流
bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
System.out.println(bos.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
檔案上傳
伺服器端
public static void main(String[] args) throws IOException {
//1. 建立服務
ServerSocket serverSocket = new ServerSocket(9000);
//2. 監聽客戶端的連線
Socket socket=serverSocket.accept();//阻塞式監聽,會一直等待客戶端的連線
//3. 獲取輸入流
InputStream is = socket.getInputStream();
//4. 檔案輸出
FileOutputStream fos = new FileOutputStream(new File("receive.txt"));
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());
//5. 關閉資源
fos.close();
is.close();
socket.close();
serverSocket.close();
}
客戶端
public static void main(String[] args) throws Exception {
//1.建立一個Socket連線
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000);
//2.建立一個輸出流
OutputStream os = socket.getOutputStream();
//3.讀取檔案
FileInputStream fis = new FileInputStream(new File("C:\\Users\\12274\\Desktop\\info.txt"));
//4.寫出檔案
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[] buffer2 = new byte[2048];
int len2;
while ((len2=is.read(buffer2))!=-1){
baos.write(buffer2,0,len2);
}
System.out.println(baos.toString());
//5.關閉資源
fis.close();
os.close();
socket.close();
}
Tomcat
服務端
- 自定義 Server
- Tomcat伺服器 : Java後臺開發
客戶端
- 自定義 Client
- 瀏覽器 Browse
UDP
發簡訊:不用連線,需要知道對方的地址!
接受端:
public static void main(String[] args) throws Exception {
//1.開放埠
DatagramSocket socket = new DatagramSocket(9090);
//2.接收資料包
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);//阻塞接受
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
//關閉連線
socket.close();
}
傳送端:
public static void main(String[] args) throws Exception {
//1.建立一個Socket
DatagramSocket socket = new DatagramSocket();
//2.建個包
String msg ="hello,server!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
DatagramPacket datagramPacket = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port);
//3.傳送包
socket.send(datagramPacket);
socket.close();
}
UDP聊天
TalkSend
package com.litzhi.chat;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
/**
* @author litzhi
* @description TODO
* @modified By
* @since Created in 2020/11/21 13:31
*/
public class TalkSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader =null;
private int fromPort;
private String toIP;
private int toPort;
public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(fromPort);
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
//準備資料: 控制檯讀取 System.in
while (true) {
try {
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));
socket.send(packet);
if (data.equals("bye")){
break;
}
}
catch (Exception e){
e.printStackTrace();
}
}
socket.close();
}
}
TalkReceive
package com.litzhi.chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
/**
* @author litzhi
* @description TODO
* @modified By
* @since Created in 2020/11/21 13:36
*/
public class TalkReceive implements Runnable {
DatagramSocket socket =null;
private int port;
private String msgFrom;
public TalkReceive(int port,String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
//準備接受包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);
//斷開連線 bye
byte[] data = packet.getData();
String receiveData = new String(data,0, packet.getLength());
System.out.println(msgFrom+": "+receiveData);
if(receiveData.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
開啟兩個執行緒
public static void main(String[] args) {
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"Teacher")).start();
}
URL
www.baidu.com
統一資源定位符:定位資源的,定位網際網路上的某一資源
DNS 域名解析 www.baidu.com xxx.xxx.xxx.xxx
協議: //ip地址:port/專案名/資源
public static void main(String[] args) throws Exception {
URL url = new URL("Http://localhost:8080/test/test.txt");
System.out.println(url.getProtocol());//協議
System.out.println(url.getHost());//主機ip
System.out.println(url.getPort());//埠
System.out.println(url.getPath());//檔案
System.out.println(url.getFile());//全路徑
System.out.println(url.getQuery());//引數
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("test.txt");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))==-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}