一、概述
-
計算機網路
計算機網路是指將地理位置不同的具有獨立功能的多臺計算機及其外部設備,通過通信線路連接起來,在網路作業系統,網路管理軟體及網路通信協議的管理和協調下,實作資源共享和資訊傳遞的計算機系統
-
網路編程的目的:
無限電臺…傳播交流資訊,資料交換,通信
二、網路通信的要素
如何實作網路的通信?
1、通信雙方地址:
-
IP
-
埠號
2、規則:網路通信的協議
TCP/IP參考模型:

小結:
網路編程中有兩個主要的問題
-
如何準確的定位到網路上的一臺或者多臺主機
-
找到主機之后如何進行通信
網路編程中的要素
-
IP 和 埠號
-
網路通信協議
萬物皆物件
- IP和網路通信協議都可以生成物件
三、IP
-
唯一定位一臺網路上計算機
-
127.0.0.1:本機localhost
-
ip地址的分類
ipv4/ipv6
- IPV4:127.0.0.1,4個位元組組成,0~255,總共42億;30億都在北美,亞洲4億,2011年就已經用盡
- IPV6:128位,8個無符號整數,例:2001:acca:0ac1:0002:0ab7:1153:2210:ccc1
公網(互聯網)-私網(局域網)
-
ABCD類地址
-
192.168.xxx.xx 專門給組織內部使用
-
域名:解決記憶IP問題!
IP:www.xxx.com 方便記錄
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
//測驗IP
//由于沒有構造器,不能new出來,只能利用靜態方法
public class TestInetAddress {
public static void main(String[] args) {
try {
//查詢本機地址
InetAddress inetAddress1 = InetAddress.getByName("127.0.0.1");
System.out.println(inetAddress1);
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(Arrays.toString(inetAddress2.getAddress())); //回傳一個陣列
System.out.println(inetAddress2.getCanonicalHostName()); //規范的名字
System.out.println(inetAddress2.getHostAddress()); //ip
System.out.println(inetAddress2.getHostName()); //域名,或者自己電腦的名字
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
}
四、埠
埠表示計算機上的一個程式的行程;
-
不同的行程有不同的埠!用來區分軟體!
-
被規定0 ~ 65535,不能使用相同的埠
-
TCP,UDP:65535*2,tcp : 80,udp : 80 這樣不影響,單個協議下,埠號不能沖突
-
埠分類
-
公有埠 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" #查看指定埠的行程
-
//埠
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",8080);
System.out.println(socketAddress);
System.out.println(socketAddress2);
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getHostName()); //地址
System.out.println(socketAddress.getPort()); //埠
}
五、通信協議
- 協議:約定,雙方使用相同可識別的語言
網路通信協議:速率、傳輸碼率、代碼結構、傳輸控制… …
主要使用:TCP/IP協議簇:實際上是一組協議
主要:
-
TCP:用戶傳輸協議 {類似于打電話,需要兩邊進行連接}
-
UDP:用戶資料報協議 {類似于發短信,不需要兩邊連接也可以發出,但不一定能送到}
-
IP:網路互連協議
TCP 與 UDP 對比
TCP:打電話
-
連接、穩定
-
三次握手、四次揮手
最少需要三次,保證穩定連接
A—— 我要連接 ——>B
B—— 你可以連接 ——>A
A—— 那我連接了 ——>B
連接成功!
四次揮手
A—— 我要斷開 ——>B
B—— 你可以斷開 ——>A
B—— 你確定斷開?——>A
A—— 我確定斷開!——>B
連接斷開
-
客戶端、服務端:主動和被動的程序
-
傳輸完成,釋放連接,效率低
UDP:發短信
-
不連接、不穩定
-
客戶端、服務端:沒有明確的界限
-
不管有沒有準備好,都可以發給你
-
DDOS:洪水攻擊!(飽和攻擊)
六、TCP
服務器
-
建立服務的埠 ServerSocket
-
等待用戶的連接 accept
-
接收用戶的資訊
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
//服務端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1.建立一個地址
serverSocket = new ServerSocket(9999);
int i = 0;
while (true){
//2.等待客戶端連接過來
System.out.println("等待客戶端連接");
socket = serverSocket.accept();
//3.讀取客戶端的資訊
i++;
is =socket.getInputStream();
System.out.println("讀取資訊成功"+i);
//管道流獲得資訊
baos = new ByteArrayOutputStream();
//創建一個接收資料的byte[]陣列,及陣列的有效長度len
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1){
baos.write(buffer, 0, len);
}
System.out.println(baos.toString());
}
}
/*//一種方法
//創建一個接收資料的byte[]陣列,及陣列的有效長度len
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer))!=-1){
String msg = new String(buffer,0,len);
System.out.println(msg);
}*/
catch (IOException e) {
e.printStackTrace();
}finally {
//關閉資源,先開后關,后開先關,
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 (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
客戶端
-
連接服務器 Socket
-
發送訊息
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
//客戶端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket = null;
OutputStream os = null;
try {
//1.要知道服務器的地址,和埠號
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
//2.創建一個 socket 連接
socket = new Socket(serverIP, port);
System.out.println("客戶端連接成功");
//3.發送訊息 IO 流
os = socket.getOutputStream();
os.write("你好,我是客戶端!".getBytes());
System.out.println("已發送");
} catch (IOException e) {
e.printStackTrace();
}
//保證代碼的嚴謹性
if (socket!= null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ServerSocket 建立服務的埠
ServerSocket.accept 阻塞監聽等待連接
Socket 創建連接
.getInputStream IO輸入流
.getOutputStream IO輸出流
ByteArrayOutputStream byte型別陣列管道輸出流
檔案上傳
服務器端
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws IOException {
//1.創建服務
ServerSocket serverSocket = new ServerSocket(9000);
//2.監聽客戶端的連接
System.out.println("等待連接");
Socket socket = serverSocket.accept(); //阻塞式監聽,會一直等待客戶端連接
//3.獲取輸入流
InputStream is = socket.getInputStream();
//檔案輸出
FileOutputStream fos = new FileOutputStream(new File("321.jpg"));
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());
//關閉資源
os.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
客戶端
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception {
//1.創建一個Socket連接
// Socket(主機--埠號)
//InetAddress.getByNam(主機--IP地址)
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);
//2.創建一個輸出流
OutputStream os = socket.getOutputStream();
//3.讀取檔案
FileInputStream fis = new FileInputStream(new File("123.jpg"));
//4.寫出檔案
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) != -1){
os.write(buffer, 0, len);
}
/*
傳輸完后,通知服務器
確定服務器接收完畢,才能斷開連接
*/
//客戶端已經傳輸完畢
socket.shutdownOutput();
//接收服務端完畢資訊
InputStream inputStream = socket.getInputStream();
//由于收到的式String byte[]陣列,使用byte輸出管道流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
while((len2 = inputStream.read(buffer)) != -1){
baos.write(buffer, 0, len2);
}
System.out.println(baos.toString());
//關閉資源
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
七、UDP
發短信:不用連接,只需要知道對方的地址!
發送端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
//1.建立一個socket
DatagramSocket socket = new DatagramSocket();
//1.2建立一個能發送的包
//發送的資料,地址
String msg = "你好啊,服務器!";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 9090;
//包的內容:資料,資料長度,要發送給誰
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
//2.發送包
socket.send(packet);
//關閉流
socket.close();
}
}
接收端:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
//開放埠
//等待客戶端的連接
DatagramSocket socket = new DatagramSocket(9090);
//接收資料包
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();
}
}
持續發送
持續發送端
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(8888);
while(true){
//準備資料:控制臺讀取 System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//發包內資料
String data = https://www.cnblogs.com/zhangwanpeng/archive/2022/01/22/reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
//發送包
socket.send(packet);
if (data.equals("bye")){
break;
}
}
//關閉流
socket.close();
}
}
持續接收端
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UdpReceiveDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6666);
while(true){
//準備接收包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
//阻塞式接收
socket.receive(packet);
//斷開連接
//將接收包轉換為 String 格式
byte[] data = https://www.cnblogs.com/zhangwanpeng/archive/2022/01/22/packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(receiveData);
if (receiveData.equals("bye")){
break;
}
}
socket.close();
}
}
多執行緒發送(相互通信)
發送執行緒
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
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);
//準備資料:控制臺讀取 System.in
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while(true){
//發包內資料
String data = https://www.cnblogs.com/zhangwanpeng/archive/2022/01/22/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();
}
}
接收執行緒
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
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() {
try {
while(true){
//準備接收包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
//阻塞式接收
socket.receive(packet);
//斷開連接
//將接收包轉換為 String 格式
byte[] data = https://www.cnblogs.com/zhangwanpeng/archive/2022/01/22/packet.getData();
String receiveData = new String(data, 0, data.length);
System.out.println(msgfrom +":" + receiveData);
if (receiveData.equals("bye")) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
socket.close();
}
}
學生執行緒
public class TalkStudent {
public static void main(String[] args) {
//學生同時開啟兩個執行緒
//學生自己的發送埠、接收IP、接收埠
new Thread(new TalkSend(6666, "localhost", 9999)).start();
//學生自己接收埠、發送過來者
new Thread(new TalkReceive(8888, "老師")).start();
}
}
教師執行緒
public class TalkTeacher {
public static void main(String[] args) {
//老師
//老師自己的發送埠、接收IP、接收埠
new Thread(new TalkSend(7777, "localhost", 8888)).start();
//老師自己接收埠、發送過來者
new Thread(new TalkReceive(9999, "學生")).start();
}
}
八、URL
統一資源定位符:定位資源的,定位互聯網上的某一個資源, 例:百度https://www.baidu.com/
DNS 域名決議:www.baidu.com == xxx.x…x…x 的IP號
協議:(https)//ip地址:埠/專案名/資源
URL常用方法
import java.net.MalformedURLException;
import java.net.URL;
public class DRLDemo01 {
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=roc&password=123");
//協議http
System.out.println(url.getProtocol());
//主機ip,localhost
System.out.println(url.getHost());
//埠,8080
System.out.println(url.getPort());
//檔案,/helloworld/index.jsp
System.out.println(url.getPath());
//全路徑,/helloworld/index.jsp?username=roc&password=123
System.out.println(url.getFile());
//引數,username=roc&password=123
System.out.println(url.getQuery());
}
}
URL網路下載
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.下載地址
URL url = new URL("https://**1.**2.com/**/**/***.jpg");
//2.連接到這個資源 HTTP
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.輸入流
InputStream inputStream = urlConnection.getInputStream();
//4.下載到存放地址(本地)
FileOutputStream fos = new FileOutputStream("123.jpg");
//5.寫出資料
byte[] buffer = new byte[1024];
int len ;
while((len = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
inputStream.close();
urlConnection.disconnect(); //斷開連接
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419021.html
標籤:其他
下一篇:初始Python系列
