Section I overview of network communication
1.1 software structure
Network programming is a program that realizes the communication between two computers under a certain protocol
C/S structure: the full name is Client/Server structure, which refers to client and server structure. Common programs include QQ... And other software
B/S structure: the full name is Browser/Server structure, which refers to browser and server structure. Common browsers include Google... And so on
1.2 network communication protocol
Network communication protocol: multiple computers can be connected through computer network. Computers located in the same network need to abide by certain rules when connecting and communicating. In the computer network, these connection and communication rules are called network communication protocol. It makes unified provisions on the transmission format, transmission rate and transmission steps of data. Both sides of communication must abide by them at the same time to complete the data exchange
TCP/IP protocol: Transmission Control Protocol / Internet Interconnection Protocol, which is the most basic and extensive protocol on the Internet
The full name of UDP protocol is user datagram protocol. In the network, it is used to process packets like TCP protocol. It is a connectionless protocol. In the OSI model, the transport layer, the fourth layer, is the upper layer of the IP protocol. UDP does not provide packet Grouping, assembly and sorting. That is to say, after the message is sent, it is impossible to know whether it arrives safely and completely.
The full name of TCP protocol is transmission control protocol. It is a connection oriented, reliable and byte stream based transport layer communication protocol, which is defined by RFC 793 of IETF. TCP is a connection oriented and reliable streaming protocol. Flow refers to the uninterrupted data structure. You can think of it as the water flow in the drainage pipe
1.3 three elements of network programming
Protocol: the rules that must be observed in computer network communication
IP address: refers to the internet protocol address. IP address is used to make a unique number for computer equipment in a network
Port number: it can uniquely identify the process (application) in the device
Section 2 TCP communication
TCP communication: connection oriented communication. The client and server must shake hands three times and establish a logical connection before communication (Security)
Communication steps:
The server starts first. The server will not actively request the client. The client must be used to request the server
A logical connection will be established between the client and the server, and this connection contains an object, which is an IO object
The client and server can use IO objects for communication. The data to be communicated is not just characters, so IO objects are byte stream objects
TCP communication client: send connection request to the server, send data to the server, and read the data written back by the server
Class representing the client:
java.net.Socket: this class implements client socket, which is the endpoint of communication between two machines
Socket: a network unit that contains an IP address and port number
Construction method:
Socket(String host, int port) creates a stream socket and connects it to the specified port number on the specified host
Parameters:
String host: name of the server host / IP address of the server
int port: the port number of the server
Member method:
OutputStream getOutputStream() returns the output stream of this socket
InputStream getInputStream() returns the input stream of this socket
void close() closes the socket
Implementation steps:
1. Create a client object Socket, and the construction method binds the IP address and port number of the server
2. Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
3. Use the write method in the OutputStream object of the network byte output stream to send data to the server
4. Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
5. Use the read method in the InputStream object of the network byte input stream to read the data written back by the server
6. Free resources (Socket)
be careful:
1. When interacting with the server, the client must use the network flow provided in the Socket, not the flow object created by itself
2. When we create a client object Socket, we will ask the server to establish a connection path through three handshakes
At this time, if the server is not started, an exception will be thrown
If the server is started, you can interact
public class TCPClient { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1",8888); OutputStream os = socket.getOutputStream(); os.write("Hello, little pine lion".getBytes(StandardCharsets.UTF_8)); InputStream is = socket.getInputStream(); byte[] bytes = new byte[1024]; int len = is.read(bytes); System.out.println(new String(bytes,0, len)); socket.close(); } }
Server side of TCP communication: receive the request from the client, read the data sent by the client, and write back the data to the client
Class representing the server:
java.net.ServerSocket: this class implements the server socket
Construction method:
ServerSocket(int port) creates a server socket bound to a feature port
The server side must be clear about one thing. It must know which client requests the server
Therefore, you can use the accept method to obtain the requested client object Socket
Member method:
Socket accept() listens and receives connections to this socket
Implementation steps of the server:
1. Create the server ServerSocket object and the port number to be specified by the system
2. Use the method accept in the ServerSocket object to obtain the requested client object Socket
3. Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object
4. Use the read method in the InputStream object of the network byte input stream to read the data sent by the client
5. Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object
6. Use the write method in the OutputStream object of the network byte output stream to write back data to the client
7. Release resources (Socket,ServerSocket)
public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); byte[] bytes = new byte[1024]; int len = is.read(bytes); System.out.println(new String(bytes,0, len)); OutputStream os = socket.getOutputStream(); os.write("Hello, Koi".getBytes(StandardCharsets.UTF_8)); socket.close(); serverSocket.close(); } }
Section III comprehensive case (file upload)
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; /* The client of the file upload case: read the local file, upload it to the server, and read the data written back by the server to make clear: Data source: local files Destination: Server Implementation steps: 1,Create a local byte input stream FileInputStream object and bind the data source to be read in the construction method 2,Create a client Socket object and bind the IP address and port number of the server in the construction method 3,Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object 4,Use the read method in the FileInputStream object of the local byte input stream to read the local file 5,Use the write method in the OutputStream object of the network byte output stream to upload the read file to the server 6,Use the method getInputStream in Socket to obtain the InputStream object of network byte input stream 7,Use the read method in the InputStream object of the network byte input stream to read the data written back by the service 8,Release resources (FileInputStream, Socket) */ public class TCPClient { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("D:\\Test\\src\\Day17\\Demo07\\IL.jpg"); Socket socket = new Socket("127.0.0.1",8888); OutputStream os = socket.getOutputStream(); int len = 0; byte[] bytes = new byte[1024]; while ((len = fis.read(bytes)) != -1){ os.write(bytes,0,len); } //Blocking occurs and is in an dead cycle state //Solution: after uploading the file, write an end mark to the server socket.shutdownOutput(); InputStream is = socket.getInputStream(); while ((len = is.read(bytes)) != -1){ System.out.println(new String(bytes, 0, len)); } fis.close(); socket.close(); } }
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; /* Server side of file upload case: read the file uploaded by the client, save it to the hard disk of the server, and write back "upload succeeded" to the client to make clear: Data source: files uploaded by the client Destination: server's hard disk Implementation steps: 1,Create a server ServerSocket object and the port number to be specified by the system 2,Use the method accept in the ServerSocket object to obtain the requested client Socket object 3,Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object 4,Judge whether the folder exists, and create if it does not exist 5,Create a local byte output stream FileOutputStream object and bind the destination to be output in the construction method 6,Use the read method in the InputStream object of the network byte input stream to read the file uploaded by the client 7,Use the write method in the FileOutputStream object of the local byte output stream to save the read file to the hard disk of the server 8,Use the method getOutputStream in the Socket object to obtain the network byte output stream OutputStream object 9,Use the write method in the OutputStream object of the network byte output stream to upload "write back" to the client successfully“ 10,Release resources (FileOutputStream, Socket, ServerSocket) */ public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); File file = new File("D:\\Test\\src\\Day18\\Demo\\upload"); if (!file.exists()){ file.mkdirs(); } FileOutputStream fos = new FileOutputStream(file + "\\IL.jpg"); int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1){ fos.write(bytes,0, len); } OutputStream os = socket.getOutputStream(); os.write("Upload successful".getBytes(StandardCharsets.UTF_8)); fos.close(); socket.close(); serverSocket.close(); } }
Case optimization
public class TCPServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); /* Keep the server listening (dead loop accept method) When a client uploads a file, it saves a file */ while (true){ Socket socket = serverSocket.accept(); /* Use multithreading technology to improve the efficiency of the program When a client uploads a file, it starts a thread to complete the file upload */ new Thread(new Runnable() { @Override public void run() { try { InputStream is = socket.getInputStream(); File file = new File("D:\\Test\\src\\Day18\\Demo\\upload"); if (!file.exists()){ file.mkdirs(); } /* Customize the naming rules of a file: prevent files with the same name from being overwritten Rule: domain name + millisecond value + random number */ String fileName = "Little pine lion" + System.currentTimeMillis() + new Random().nextInt(99999) + ".jpg"; //FileOutputStream fos = new FileOutputStream(file + "\\IL.jpg"); FileOutputStream fos = new FileOutputStream(file + "\\" + fileName); int len = 0; byte[] bytes = new byte[1024]; while ((len = is.read(bytes)) != -1){ fos.write(bytes,0, len); } OutputStream os = socket.getOutputStream(); os.write("Upload successful".getBytes(StandardCharsets.UTF_8)); fos.close(); socket.close(); }catch (IOException e){ System.out.println(e); } } }).start(); } //The server doesn't have to be shut down //serverSocket.close(); } }
Section IV simulated BS server case
Access page address: http://127.0.0.1:8080/ (file address) html
import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; public class TCPServer { public static void main(String[] args) throws IOException { //Create a server ServerSocket and the port number to be specified by the system ServerSocket serverSocket = new ServerSocket(8080); /* The browser parses the html page written back by the server. If there are pictures in the page, the browser will open a separate thread to read the pictures of the server We have to keep the server listening. The server writes back once the client requests it */ while (true){ //Use the accept method to get the requested client object (browser) Socket socket = serverSocket.accept(); new Thread(new Runnable() { @Override public void run() { try { //Use the method getInputStream in the Socket object to obtain the network byte input stream InputStream object InputStream is = socket.getInputStream(); //Convert the is network byte input stream object into character buffer input stream BufferedReader br = new BufferedReader(new InputStreamReader(is)); //Read the first line of the client request information String line = br.readLine(); //Cut the read information, as long as the middle part String[] arr = line.split(" "); //Remove the / in front of the path and intercept it String htmlPath = arr[1].substring(1); //Create a local byte input stream and bind the html path to be read in the construction method FileInputStream fis = new FileInputStream(htmlPath); //Use the method getOutputStream in the Socket to obtain the network byte output stream OutputStream object OutputStream os = socket.getOutputStream(); //Write HTTP protocol response header, fixed writing method os.write("HTTP/1.1 200 OK\r\n".getBytes(StandardCharsets.UTF_8)); os.write("Content-Type:text/html\r\n".getBytes(StandardCharsets.UTF_8)); //You must write a blank line, or the browser will not parse it os.write("\r\n".getBytes(StandardCharsets.UTF_8)); //Copy the file by reading and writing, and write back the html file read by the server to the browser int len = 0; byte[] bytes = new byte[1024]; while ((len = fis.read(bytes)) != -1){ os.write(bytes,0, len); } fis.close(); socket.close(); }catch (IOException e){ e.printStackTrace(); } } }).start(); } //serverSocket.close(); } }