java成神之路——網絡編程
一 、什么是計算機網絡

計算機網絡是指將地理位置不同的具有獨立功能的多臺計算機及其外部設備,通過通信線路連接起來,在網絡操作系統,網絡管理軟件及網絡通信協議的管理和協調下,實現資源共享和信息傳遞的計算機系統。
實現傳播交流信息,數據交換、通信
IP地址 + port 定位到這臺計算機的某個資源
eg:192.168.16.124:8080
二 、網絡通信要素
1 、 通信雙方地址 : IP + port
2 、 網絡通信的協議
TCP/IP參考模型
我們這篇博客主要是針對傳輸層
三 、IP
IP地址 :InetAddress
唯一定位一臺計算機
127.0.0.1 /localhost 本機地址
ip地址分類
1 、 ipv4 : 四個字節組成(1byte = 8bit),每個字節的范圍是0 - 255 (1X27+1X26+1X25+1X24+1X23+lX22+1 X21+1X20=255);ipv4一共有42億,但是30億都在北美,亞洲4億,2011年就用完了,所以有了IPV6
2、IPV6 : 128位,8位無符號整數
eg ; 2001 :obba :1284:0000:0000:1aaa:2aaa:1524
公網 (互聯網)、私網(局域網)
* ABCD 類地址 * 192.168.XX.xx 專門給組織內部使用
1
2
域名:解決IP記憶問題
與IP相關的類 InetAddress
package intentp; import Java.net.InetAddress; import Java.net.UnknownHostException; public class testInternrt { public static void main(String[] args) { try { //查詢ip地址 InetAddress address = InetAddress.getByName("127.0.0.1"); InetAddress address1 = InetAddress.getByName("www.baidu.com"); InetAddress localHost = InetAddress.getLocalHost(); System.out.println(address1); System.out.println(address); System.out.println(localHost); System.out.println(InetAddress.getAllByName("127.0.0.1")); } catch (UnknownHostException e) { e.printStackTrace(); } } } 一個程序進程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
四 端口port
我們可以將端口理解為表示計算機上的一個進程
* 不同的進程有不同的端口號! * 被規定:0 ——65535 * TCP/ UDP :65535 * 2 單個協議下端口號不能相同 * 端口分類 ** 共有端口0-1023 ** HTTP :80(默認端口) ** HTTPS :443 (默認端口) ** FTP: 21 ** Telent : 23 * 程序注冊端口:1024-49151 * Tomcat 8080 * Mysql 3306 * Oracle : 1521 * 動態私有 : 49152 - 65535 *關于端口常見的dos命令 * netstat -ano 查看所有的端口 * netstat -ano |findstr "port" 查找指定的端口 * tasklist|findstr "port“” 查看指定端口的進程 * taskkill -pid 進程號 -f 殺死端進程 * ctr + shift +esc 打開任務管理器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package intentp; import java.net.InetSocketAddress; /** *C:\Windows\System32\drivers\etc 里面的host文件可以配置本機的映射地址 * 127.0.0.1 www.sso.com */ public class InetSocketAddressTest { public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("localhost", 8080); InetSocketAddress socketAddress2 = new InetSocketAddress("127.0.0.1", 8080); System.out.println(socketAddress); System.out.println(socketAddress2); System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName()); System.out.println(socketAddress.getPort()); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
這里給大家說一下如何配置本機地址的映射
打開我的電腦——》C盤——》System32——》drivers——》etc 找到host文件,在里面添加映射就可以了
五 、通信協議
協議:可以理解為一中約定,約定以雙方能懂的方式進行交流
TCP/IP協議簇
TCP : 用戶傳輸協議
UDP : 用戶數據協議報
TCP/UDP對比
TCP :
連接、穩定
三次握手
四次揮手
客戶端 、服務端
傳輸完成、釋放連接、效率低
UDP:
不連接、不穩定
客戶端、服務端 沒有明確的界限
不管有沒有準備好都可以發送給你
比如:DDOS 洪水攻擊
TCP實現聊天
TCP實現客戶端和服務端之間的通信
package intentp; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; /** * TCP: 實現聊天 * client: * server: * */ //客戶端 public class TcpClientDemo { public static void main(String[] args) { //要知道服務器的地址 Socket socket = null; OutputStream os = null; try { InetAddress serverip = InetAddress.getByName("127.0.0.1"); int port = 9999; //傳建一個scoket連接 socket = new Socket(serverip,port); //發消息 os = socket.getOutputStream(); os.write("你好服務器".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { if (os != null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package intentp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //服務端 public class TcpServerDemo { public static void main(String[] args) { ServerSocket serverSocket = null; Socket accept = null; InputStream inputStream = null; ByteArrayOutputStream baos = null; // 有一個地址 try { serverSocket = new ServerSocket(9999); //等待客戶端連接 accept = serverSocket.accept(); //接收消息 inputStream = accept.getInputStream(); /* //這樣寫 萬一內容超過1024就容易斷開 byte[] bytes = new byte[1024]; int len ; while((len = inputStream.read(bytes)) != -1){ String s = new String(bytes, 0, len); System.out.println(s); }*/ baos = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = inputStream.read(bytes)) != -1){ baos.write(bytes,0,len); } System.out.println(baos.toString()); } catch (IOException e) { e.printStackTrace(); }finally { if (baos != null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (accept != null){ try { accept.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
TCP實現文件傳輸
package intentp; import java.io.*; import java.net.InetAddress; import java.net.Socket; /** * TCP文件上傳 * */ public class TcpFileClientDemo { public static void main(String[] args) throws Exception{ //創建一個socket連接 Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000); //創建一個輸出流 OutputStream os = socket.getOutputStream(); //文件流 FileInputStream fileInputStream = new FileInputStream(new File("class2.png")); byte[] bytes = new byte[1024]; int len = 0; while((len=fileInputStream.read(bytes)) != -1){ os.write(bytes,0,len); } //通知服務器我已經結束了 socket.shutdownOutput();//我已經傳輸完了 //確定服務器接收完畢 InputStream iss = socket.getInputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = iss.read(bytes)) != -1){ bos.write(bytes,0,len); } System.out.println(bos.toString()); //關閉資源 bos.close(); iss.close(); fileInputStream.close(); os.close(); socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package intentp; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * TCP 傳輸文件服務器端 */ public class TcpFileServerDemo { public static void main(String[] args) throws Exception{ //建立一個地址--->創建服務 ServerSocket socket = new ServerSocket(9000); //等待連接------》監聽服務(阻塞監聽) Socket accept = socket.accept(); //接收消息 InputStream is = accept.getInputStream(); FileOutputStream fos = new FileOutputStream(new File("receive.png")); byte[] bytes = new byte[1024]; int len; while((len = is.read(bytes)) != -1){ fos.write(bytes,0,len); } //通知客戶端我接受完了 OutputStream oss = accept.getOutputStream(); oss.write("我接收完了,你可以斷開了".getBytes()); oss.close(); fos.close(); is.close(); accept.close(); socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
UDP消息發送
package intentp; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /** * Tomcat 完全由java寫的 * UDP 不用連接 服務器 * 建立socket * 建立一個包 * 發送包 * 主要方法 data報包 * */ public class UdpClientDemo { public static void main(String[] args) throws Exception { //建立socket DatagramSocket socket = new DatagramSocket(9090); //建立一個包 //發送給誰 //發送什么 String mssage = "我是UDP不建立連接"; InetAddress localhost = InetAddress.getByName("localhost"); int port = 9090; DatagramPacket packet = new DatagramPacket(mssage.getBytes(),0,mssage.getBytes().length,localhost,port); //發送包 socket.send(packet); //關閉資源 socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
UDP中客戶端和服務端沒有明確的界限
package intentp; import java.net.DatagramPacket; import java.net.DatagramSocket; /** * UDP 沒有真正的client 和server 概念 * 還是要等待客戶端的連接 */ public class UdpServerDemo { public static void main(String[] args) throws Exception{ //開放端口 DatagramSocket socket = new DatagramSocket(9090); //接收數據 byte[] bytes = new byte[1024]; //接到哪里 DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length); socket.receive(packet); System.out.println(packet.getAddress().getHostAddress()); System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
UDP實現聊天
package chat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class UdpSendDemo { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(8888); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true){ String s = reader.readLine(); byte[] bytes = s.getBytes(); //建立一個包 //發送給誰 //發送什么 DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,new InetSocketAddress("localhost",6666)); socket.send(packet); if (bytes.equals("bye")){ break; } } socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package chat; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpResceiveDemo { public static void main(String[] args) throws Exception{ DatagramSocket socket = new DatagramSocket(6666); while (true){ byte[] bytes = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length); socket.receive(datagramPacket); byte[] data = datagramPacket.getData(); String s = new String(data, 0, data.length); System.out.println(s); if (s.equals("bye")){ break; } } socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
UDP多線程在線咨詢
TALKSEND
package chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class TalkSened implements Runnable { DatagramSocket socket = null; BufferedReader reader = null; private String toIp; private int toProt; private int fromProt; public TalkSened(String toIp, int toProt, int fromProt) { this.toIp = toIp; this.toProt = toProt; this.fromProt = fromProt; try { socket = new DatagramSocket(this.fromProt); reader = new BufferedReader(new InputStreamReader(System.in)); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while (true){ String s = null; try { s = reader.readLine(); byte[] bytes = s.getBytes(); DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length,new InetSocketAddress(this.toIp,this.toProt)); socket.send(packet); if (bytes.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
TALKRECEVIE
package chat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TalkReceive implements Runnable { DatagramSocket socket = null; private int fromProt; private String fromMessge; public TalkReceive(int fromProt,String fromMessge) { this.fromProt = fromProt; this.fromMessge = fromMessge; try { socket = new DatagramSocket(this.fromProt); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while (true){ try { byte[] bytes = new byte[1024]; DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length); socket.receive(datagramPacket); byte[] data = datagramPacket.getData(); String s = new String(data, 0, data.length); System.out.println(fromMessge+":"+ s); if (s.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
學生
package chat; public class TalkStudent { public static void main(String[] args) { TalkSened talkSened = new TalkSened("localhost", 9999, 7777); TalkReceive talkReceive = new TalkReceive(8888, "老師"); new Thread(talkSened).start(); new Thread(talkReceive).start(); } }
1
2
3
4
5
6
7
8
9
10
11
12
老師
package chat;
public class TalkTeacher {
public static void main(String[] args) {
TalkSened talkSened = new TalkSened(“localhost”, 8888, 5555);
TalkReceive talkReceive = new TalkReceive(9999, “學生”);
new Thread(talkSened).start();
new Thread(talkReceive).start();
}
1
}
URL下載網絡資源
import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class Url { public static void main(String[] args) throws Exception { URL url = new URL("https://www.baidu/XXXX);//這里寫下載資源的網絡地址 //連接到這個資源 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream("f.m4a"); byte[] bytes = new byte[1024]; int len; while ((len = inputStream.read(bytes)) != -1){ fos.write(bytes,0,len); } fos.close(); inputStream.close(); urlConnection.disconnect(); } }
Java 網絡
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。