Port(PID)
1
2
3
4
| netstat -ano #查看所有端口
netstat -ano|findstr "6732" #查看指定端口
tasklist|findstr "6732" #查看指定进程
# 使用任务管理器查看PID
|
端口号与IP地址的组合,得出一个网络套接字:Socket,所以说一些网络编程也被称为Socket编程
1
2
3
4
5
6
7
8
9
10
11
| import java.net.InetSocketAddress;
public class InetSocketAddressTest {
public static void main(String[] args) {
InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080);
InetSocketAddress socketAddress2 = new InetSocketAddress("localhost",9000);
System.out.println(socketAddress.getHostName());
System.out.println(socketAddress.getAddress());
System.out.println(socketAddress.getPort());
System.out.println(socketAddress2.getHostName()); System.out.println(socketAddress2.getAddress()); //返回地址 System.out.println(socketAddress2.getPort()); //返回端口
}
}
|
Protocal
1. TCP Demo
1.1 Client Demo1
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
| import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//客户端
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 = 8899;
//2. 创建一个Socket
socket = new Socket(serverIP,port);
//3. 创建一个输出流,向外写东西
os = socket.getOutputStream();
os.write("你好,欢迎学习狂神说Java".getBytes());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//4. 关闭资源
try {
if (os!=null){
os.close();
}
if (socket!=null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
1.2. Server Demo1
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
| 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 accept = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
try {
//1. 开放服务器端口,创建ServerSocket
serverSocket = new ServerSocket(8899);
while (true) {
//2. 等待客户端的连接
accept = serverSocket.accept();
//3. 读入客户端的消息,
is = accept.getInputStream();
/* 回忆之前的IO流方案,弊端:存在中文,可能存在乱码。 byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
String str = new String(buffer,0,len);
System.out.println(str);
}
**/
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
System.out.println("数据来源地址:"+accept.getInetAddress().getHostName());
}
} catch (IOException e) {
e.printStackTrace();
} finally { //4. 关闭资源
try {
if (baos!=null){
baos.close();
}
if (is!=null){
is.close();
}
if (accept!=null){
accept.close();
}
if (serverSocket!=null){
serverSocket.close();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
1.3 Client Demo2
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 15:33:20
* @LastEditTime: 2022-09-11 02:43:36
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TcpClientDemo02.java
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
// 1. 创建server连接
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
// 2. 创建一个输出流
OutputStream os = socket.getOutputStream();
// 3. 读取文件
FileInputStream fis = new FileInputStream(new File("textfile.txt"));
// 4. 写出文件
byte[] buffer = new byte[1024];
int len;
// file has EOF, so fis.read() will not block
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
// tell server the output stream is over and close output,
// otherwise server will always be waiting
socket.shutdownOutput();
// wait for server to reply, and respond to console
// System.out.println("I can get there!");
InputStream inputStream = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer2 = new byte[1024];
int len2;
// Why server doesn't shut down its outputStream but this won't get blocked?
// because the server will end its function and close, then the inputStream will not block
while ((len2 = inputStream.read(buffer2)) != -1) {
baos.write(buffer2, 0, len2);
// System.out.println("I can get there!");
}
System.out.println("I can get there!");
System.out.println(baos.toString());
// 5. 资源关闭,应该使用try-catch-finally
baos.close();
inputStream.close();
fis.close();
os.close();
socket.close();
}
}
|
1.4 Server Demo2
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 15:33:28
* @LastEditTime: 2022-09-11 02:40:41
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TcpServerDemo02.java
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
public class TcpServerDemo02 {
public static void main(String[] args) throws Exception{
// 1. open serverSocket
ServerSocket serverSocket = new ServerSocket(9090);
// 2. listen client socket
Socket socket = serverSocket.accept();
// 3. get inputStream
InputStream is = socket.getInputStream();
// 4. read file and writer to a new file
FileOutputStream fos = new FileOutputStream(new File("receive.txt"));
byte[] buffer = new byte[1024];
int len;
// inputStream read is block function, unless outputStream shut down or closed, will always blocked,
// not even get into the while loop once.
while ((len = is.read(buffer)) != -1) {
// System.out.println("I can get there!");
fos.write(buffer, 0, len);
}
System.out.println("I can get there!");
// tell client receive successfully
OutputStream outputStream = socket.getOutputStream();
outputStream.write("File has been received successfully!".getBytes());
TimeUnit.SECONDS.sleep(1);
outputStream.write("Can you receive this?".getBytes());
// 5. close, should use try-catch-finally
outputStream.close();
fos.close();
is.close();
socket.close();
serverSocket.close();
}
}
|
2. UDP Demo
2.1 说明
- DatagramSocket 和 DatagramPacket 两个类实现了基于UDP协议的网络程序。
- UDP 数据报通过数据报套接字 DatagramSocket 发送和接收,系统不保证UDP数据报一定能够安 全送到目的地,也不确定什么时候可以抵达。
- DatagramPacket 对象封装了UDP数据报,在数据报中包含了发送端的IP地址和端口号以及接收端 的IP地址和端口号。
- UDP协议中每个数据报都给出了完整的地址信息,因此无需建立发送方和接收方的连接。如同发快递包裹一样。
2.2 Demo1 Talking
Sender
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
| import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 17:01:23
* @LastEditTime: 2022-09-10 17:12:10
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/UdpSenderDemo01.java
*/
public class UdpSenderDemo01 {
public static void main(String[] args) throws Exception{
System.out.println("Sender start...");
// 1. create DatagramSocket
DatagramSocket socket = new DatagramSocket(8888);
// 2. encapsulate data packet
// String msg = "Udpsender==>";
// byte[] data = msg.getBytes();
// InetAddress inet = InetAddress.getByName("127.0.0.1");
// int port = 9090;
// // args: byte[], offset, length, socket(address, port)
// DatagramPacket packet = new DatagramPacket(data, 0, data.length, inet, port);
// 2. encapsulate data packet from console input
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String data = reader.readLine();
byte[] datas = data.getBytes();
// 3. encapsulate datas to DatagramPacket, send to destination
DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));
// 4. send packet to receiver
socket.send(packet);
// exit check
if (data.equals("bye")) {
break;
}
}
// 5. close
reader.close();
socket.close();
}
}
|
Receiver
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 17:12:28
* @LastEditTime: 2022-09-10 17:18:21
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/UdpReceiverDemo01.java
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpReceiverDemo01 {
public static void main(String[] args) throws Exception{
DatagramSocket socket= new DatagramSocket(6666);
while(true) {
try {
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet); // receive packet(block)
byte[] datas = packet.getData();
int len = packet.getLength();
String data = new String(datas, 0, len);
System.out.println(data);
// exit check
if (data.equals("bye")) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
|
2.3 Demo2 Multi-thread Talking
SenderThread
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 23:01:28
* @LastEditTime: 2022-09-10 23:09:24
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TalkSend.java
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class TalkSend implements Runnable {
private DatagramSocket socket;
private BufferedReader reader;
private String toIp;
private int toPort;
public TalkSend(int port, String toIp, int toPort) {
this.toIp = toIp;
this.toPort = toPort;
try {
socket = new DatagramSocket(port);
reader =new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
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();
}
}
|
ReceiverThread
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 22:24:18
* @LastEditTime: 2022-09-10 23:01:08
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TalkReceive.java
*/
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class TalkReceive implements Runnable {
private DatagramSocket socket;
private String msgFrom;
public TalkReceive(int port, String msgFrom) {
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try {
// prepare to receive packet
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container, 0, container.length);
socket.receive(packet); // block to receive packet
byte[] datas = packet.getData();
int len = packet.getLength();
String data = new String(datas, 0, len);
System.out.println(msgFrom + ":" + data + " from address: " + packet.getAddress());
// exit check
if (data.equals("bye")) {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
|
Student
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 23:09:43
* @LastEditTime: 2022-09-10 23:20:04
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TalkStudent.java
*/
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777, "localhost", 9999)).start();
new Thread(new TalkReceive(8888, "老师")).start();
}
}
|
Teacher
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-10 23:10:56
* @LastEditTime: 2022-09-10 23:12:09
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/TalkTeacher.java
*/
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkReceive(9999, "学生")).start();
new Thread(new TalkSend(5555, "localhost", 8888)).start();
}
}
|
URL
URL (Uniform Resource Locator): 统一资源定位符,它表示 internet 上某一资源的地址。 它是一种具体的URI,即URL可以用来标识一个资源,而且还指明了如何locate:定位这个资源。 通过URL, 我们可以访问Internet上的各种网络资源,比如最常见的 www, ftp 站点。浏览器通过解析给定的URL可以在网络上查找相应的文件或其他资源。 URL的基本结构由5部分组成:
传输协议://主机名:端口号/文件名 #片段名?参数列表
URL Demo
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
| /*
* @Author: Zeping Zhu
* @Andrew ID: zepingz
* @Date: 2022-09-11 00:30:43
* @LastEditTime: 2022-09-11 00:47:45
* @LastEditors: Zeping Zhu
* @Description:
* @FilePath: /JavaWebPractice/URLDemo01.java
*/
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLDemo01 {
public static void main(String[] args) {
try {
// 1. locate to ressource of server
URL url = new URL("https://p1.music.126.net/7DYwgmJyEoTJZ3pyr7lixw==/109951167430870270.jpg?param=40y40");
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()); //获取URL的查询名
// 2. create connect
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. get inputStream
InputStream is = connection.getInputStream();
// 4. write in file
FileOutputStream fos = new FileOutputStream("icon.png");
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
// close
fos.close();
is.close();
connection.disconnect();
System.out.println("closed...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|