Network programming
primary coverage
Learning objectives
Chapter 1 Introduction to network programming
1.1 software structure
B / S structure: fully known as browser / server structure, it refers to browser and server structure. Common browsers include Google, Firefox, etc.
The two architectures have their own advantages, but no matter which architecture, it is inseparable from the support of the network. Network programming is a program that realizes the communication between two computers under a certain protocol.
1.2 network communication protocol
In the figure above, the four layers of TCP / IP protocol are application layer, transmission layer, network layer and link layer, and each layer is responsible for different communication functions. Link layer: the link layer is used to define the physical transmission channel. It is usually the driving protocol for some network connection devices, such as the driver provided for optical fiber and network cable. Network layer: the network layer is the core of the whole TCP / IP protocol. It is mainly used to group the transmitted data and send the packet data to the target computer or network. Transport layer: it mainly enables network programs to communicate. TCP protocol or UDP protocol can be used for network communication. Application layer: mainly responsible for the application protocol, such as HTTP protocol, FTP protocol, etc.
1.3 protocol classification
The communication protocol is still relatively complex, Java Net package, which provides low-level communication details. We can directly use these classes and interfaces to focus on network program development without considering the details of communication.
java. Net package provides support for two common network protocols:
Features: the data is limited to 64KB, beyond which it cannot be sent.
Datagram: the basic unit of network transmission
After three handshakes are completed and the connection is established, the client and server can start data transmission. Because of this connection oriented feature, TCP protocol can ensure the security of data transmission, so it is widely used, such as downloading files, browsing web pages and so on.
1.4 three elements of network programming
agreement
IP address
IP address classification
Common commands
ipconfig
ping 空格 IP地址
ping 220.181.57.216
Special IP address
Port number
Network communication is essentially the communication between two processes (Applications). Each computer has many processes, so how to distinguish these processes in network communication?
If the IP address can uniquely identify the device in the network, the port number can uniquely identify the process (application) in the device.
Using the ternary combination of protocol + IP address + port number, the processes in the network can be identified, and the communication between processes can use this identification to interact with other processes.
Chapter II TCP communication program
2.1 general
TCP communication can realize the data interaction between two computers. The two ends of communication should be strictly divided into client and server.
Steps for communication between two ends:
In Java, two classes are provided to implement TCP communication programs:
2.2 socket class
Socket class: this class implements client socket. Socket refers to the endpoint of communication between two devices.
Construction method
For example, the code is as follows:
Socket client = new Socket("127.0.0.1",6666);
Member method
2.3 ServerSocket class
ServerSocket class: this class implements the server socket, which waits for requests through the network.
Construction method
For example, the code is as follows:
ServerSocket server = new ServerSocket(6666);
Member method
2.4 simple TCP network program
TCP communication analysis diagram
The client sends data to the server
Server implementation:
public class ServerTCP {
public static void main(String[] args) throws IOException {
System.out.println("服务端启动,等待连接 .... ");
// 1.创建 ServerSocket对象,绑定端口,开始等待连接
ServerSocket ss = new ServerSocket(6666);
// 2.接收连接 accept 方法,返回 socket 对象.
Socket server = ss.accept();
// 3.通过socket 获取输入流
InputStream is = server.getInputStream();
// 4.一次性读取数据
// 4.1 创建字节数组
byte[] b = new byte[1024];
// 4.2 据读取到字节数组中.
int len = is.read(b);
// 4.3 解析数组,打印字符串信息
String msg = new String(b,len);
System.out.println(msg);
//5.关闭资源.
is.close();
server.close();
}
}
Client implementation:
public class ClientTCP {
public static void main(String[] args) throws Exception {
System.out.println("客户端 发送数据");
// 1.创建 Socket ( ip,port ),确定连接到哪里.
Socket client = new Socket("localhost",6666);
// 2.获取流对象 . 输出流
OutputStream os = client.getOutputStream();
// 3.写出数据.
os.write("你好么? tcp,我来了".getBytes());
// 4. 关闭资源 .
os.close();
client.close();
}
}
The server writes back data to the client
Server implementation:
public class ServerTCP {
public static void main(String[] args) throws IOException {
System.out.println("服务端启动,len);
System.out.println(msg);
// =================回写数据=======================
// 5. 通过 socket 获取输出流
OutputStream out = server.getOutputStream();
// 6. 回写数据
out.write("我很好,谢谢你".getBytes());
// 7.关闭资源.
out.close();
is.close();
server.close();
}
}
Client implementation:
public class ClientTCP {
public static void main(String[] args) throws Exception {
System.out.println("客户端 发送数据");
// 1.创建 Socket ( ip,6666);
// 2.通过Scoket,获取输出流对象
OutputStream os = client.getOutputStream();
// 3.写出数据.
os.write("你好么? tcp,我来了".getBytes());
// ==============解析回写=========================
// 4. 通过Scoket,获取 输入流对象
InputStream in = client.getInputStream();
// 5. 读取数据数据
byte[] b = new byte[100];
int len = in.read(b);
System.out.println(new String(b,len));
// 6. 关闭资源 .
in.close();
os.close();
client.close();
}
}
Chapter III comprehensive cases
3.1 file upload cases
File upload analysis diagram
Basic implementation
Server implementation:
public class FileUpload_Server {
public static void main(String[] args) throws IOException {
System.out.println("服务器 启动..... ");
// 1. 创建服务端ServerSocket
ServerSocket serverSocket = new ServerSocket(6666);
// 2. 建立连接
Socket accept = serverSocket.accept();
// 3. 创建流对象
// 3.1 获取输入流,读取文件数据
BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
// 3.2 创建输出流,保存到本地 .
bufferedoutputstream bos = new bufferedoutputstream(new FileOutputStream("copy.jpg"));
// 4. 读写数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b,len);
}
//5. 关闭 资源
bos.close();
bis.close();
accept.close();
System.out.println("文件上传已保存");
}
}
Client implementation:
public class FileUPload_Client {
public static void main(String[] args) throws IOException {
// 1.创建流对象
// 1.1 创建输入流,读取本地文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.jpg"));
// 1.2 创建输出流,写到服务端
Socket socket = new Socket("localhost",6666);
bufferedoutputstream bos = new bufferedoutputstream(socket.getOutputStream());
//2.写出数据.
byte[] b = new byte[1024 * 8 ];
int len ;
while (( len = bis.read(b))!=-1) {
bos.write(b,len);
bos.flush();
}
System.out.println("文件发送完毕");
// 3.释放资源
bos.close();
socket.close();
bis.close();
System.out.println("文件上传完毕 ");
}
}
File upload optimization analysis
FileOutputStream fis = new FileOutputStream(System.currentTimeMillis()+".jpg") // 文件名称
bufferedoutputstream bos = new bufferedoutputstream(fis);
// 每次接收新的连接,创建一个Socket
while(true){
Socket accept = serverSocket.accept();
......
}
while(true){
Socket accept = serverSocket.accept();
// accept 交给子线程处理.
new Thread(() -> {
......
InputStream bis = accept.getInputStream();
......
}).start();
}
Optimized implementation
public class FileUpload_Server {
public static void main(String[] args) throws IOException {
System.out.println("服务器 启动..... ");
// 1. 创建服务端ServerSocket
ServerSocket serverSocket = new ServerSocket(6666);
// 2. 循环接收,建立连接
while (true) {
Socket accept = serverSocket.accept();
/*
3. socket对象交给子线程处理,进行读写操作
Runnable接口中,只有一个run方法,使用lambda表达式简化格式
*/
new Thread(() -> {
try (
//3.1 获取输入流对象
BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
//3.2 创建输出流对象,保存到本地 .
FileOutputStream fis = new FileOutputStream(System.currentTimeMillis() + ".jpg");
bufferedoutputstream bos = new bufferedoutputstream(fis);) {
// 3.3 读写数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b,len);
}
//4. 关闭 资源
bos.close();
bis.close();
accept.close();
System.out.println("文件上传已保存");
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
Information write back analysis diagram
The first four steps are consistent with the basic file upload
Writeback implementation
public class FileUpload_Server {
public static void main(String[] args) throws IOException {
System.out.println("服务器 启动..... ");
// 1. 创建服务端ServerSocket
ServerSocket serverSocket = new ServerSocket(6666);
// 2. 循环接收,建立连接
while (true) {
Socket accept = serverSocket.accept();
/*
3. socket对象交给子线程处理,保存到本地 .
FileOutputStream fis = new FileOutputStream(System.currentTimeMillis() + ".jpg");
bufferedoutputstream bos = new bufferedoutputstream(fis);
) {
// 3.3 读写数据
byte[] b = new byte[1024 * 8];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b,len);
}
// 4.=======信息回写===========================
System.out.println("back ........");
OutputStream out = accept.getOutputStream();
out.write("上传成功".getBytes());
out.close();
//================================
//5. 关闭 资源
bos.close();
bis.close();
accept.close();
System.out.println("文件上传已保存");
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
Client implementation:
public class FileUpload_Client {
public static void main(String[] args) throws IOException {
// 1.创建流对象
// 1.1 创建输入流,读取本地文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("test.jpg"));
// 1.2 创建输出流,写到服务端
Socket socket = new Socket("localhost",6666);
bufferedoutputstream bos = new bufferedoutputstream(socket.getOutputStream());
//2.写出数据.
byte[] b = new byte[1024 * 8 ];
int len ;
while (( len = bis.read(b))!=-1) {
bos.write(b,len);
}
// 关闭输出流,通知服务端,写出数据完毕
socket.shutdownOutput();
System.out.println("文件发送完毕");
// 3. =====解析回写============
InputStream in = socket.getInputStream();
byte[] back = new byte[20];
in.read(back);
System.out.println(new String(back));
in.close();
// ============================
// 4.释放资源
socket.close();
bis.close();
}
}