1. Overview of network programming
- Java is a language on the Internet. It provides support for network applications at the language level. Programmers can easily develop common network applications
- The network class library provided by java can realize painless network connection. The underlying details of networking are hidden in the Java Native installation system and controlled by the JVM
- Java implements a cross platform network library. Programmers face a unified network programming environment
- Computer network: connect computers distributed in different geographical areas with special external equipment with communication lines to form a large-scale and powerful network system, so that many computers can easily transfer information to each other and share hardware, software, data information and other resources
- The purpose of network programming is to realize data exchange and communication with other computers directly or indirectly through network protocol
- There are two main problems in network programming:
- How to accurately locate one or more hosts on the network; Locate a specific application on the host
- How to transmit data reliably and efficiently after finding the host
2. Overview of network communication elements
- Address of communication parties: IP + port number
- Certain rules:
- OSI reference model: the model is too idealized to be widely popularized on the Internet
- TCP/IP reference model: a de facto international standard
Communication element 1: IP and port number
IP address: InetAddress
- Uniquely identifies the computer (communication entity) on the Internet
- Local loopback address: 127.0.0.1 hostName: localhost
- IP address classification method 1: IPV4 and IPV6
- IPV4: 4 bytes, 4 0-255. About 4.2 billion and 3 billion are in North America and 400 million in Asia. It was exhausted in early 2011.
- IPV6:128 bits (16 bytes), written as 8 unsigned integers, each integer is represented by 4 hexadecimal bits, and the numbers are separated by colons. 3ffe:3201:1401:1280:c8ff:fe4d:db39:1984
- IP address classification method 2: public network address (used by the World Wide Web) and private address (used by the local area network). 192.168. The beginning is the private address, which is specially used within the organization.
- Features: not easy to remember
// How to instantiate InetAddress InetAddress localhost = InetAddress.getByName("192.168.33.249"); // Use IP address InetAddress baidu = InetAddress.getByName("www.baidu.com"); // Use domain name InetAddress localHost = InetAddress.getLocalHost(); // Get the IP address of this machine directly System.out.println(baidu.getHostName()); // www.baidu.com get domain name System.out.println(baidu.getHostAddress()); // 220.181.38.149 get IP address
Port number: identifies the process running on the computer
- Different processes have different port numbers
- Is specified as a 16 bit integer 0-65535
- Port classification
- Recognized port: 0-1023. Occupied by predefined service communication (e.g. HTTP occupies port 80, FTP occupies port 21, Telnet occupies port 23)
- Registration port: 1024-49151. Assigned to users or applications. (for example, Tomcat occupies port 8080, MySQL occupies port 3306, Oracle occupies port 1521, etc.)
- Dynamic / private port: 49152-65535.
- The combination of port number and IP address leads to a network Socket: Socket
Communication element 2: network protocol
- Network communication protocol: there must be some conventions to realize communication in computer network, that is, communication protocol, which formulates standards for rate, transmission code, code structure, transmission control steps, error control, etc.
- The idea of communication protocol layering: when formulating the protocol, the complex components are decomposed into some simple components, and then they are combined. The most commonly used composite method is the hierarchical method, that is, the same layer can communicate, the upper layer can call the next layer, and there is no relationship with the next layer. Each layer does not affect each other, which is conducive to the development and expansion of the system.
- There are two very important protocols in the transport layer protocol:
- Transmission control protocol TCP
- User datagram protocol UDP
- TCP/IP is named after its two main protocols: transmission control protocol TCP and network interconnection protocol IP. It is actually a group of protocols, including multiple protocols with different functions and related to each other.
- IP protocol is the main protocol of network layer, which supports data communication between networks.
- From a more practical point of view, TCP/IP protocol model forms an efficient four layer architecture, namely physical link layer, IP layer, transmission layer and application layer.
- TCP protocol:
- Before using TCP protocol, a TCP connection must be established to form a data transmission channel
- Before transmission, the "three-time handshake" mode is adopted for point-to-point communication, which is reliable
- Two application processes of TCP protocol communication: client and server
- A large amount of data can be transmitted in the connection
- After transmission, the established connection needs to be released, which is inefficient
- UDP protocol:
- Encapsulate the data, source and destination into data packets without establishing a connection
- The size of each datagram is limited to 64K
- Whether the sending party is ready or not, the receiving party does not confirm the receipt, so it is unreliable
- Can broadcast and send
- At the end of sending data, there is no need to release resources, low overhead and high speed
3.TCP network programming
Example 1: the client sends information to the server, and the server displays the data on the console
public void server() { ServerSocket serverSocket = null; Socket accept = null; InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; try { // 1. Create a Socket on the server side and indicate its own port number serverSocket = new ServerSocket(11223); // 2. Receive Socket from client accept = serverSocket.accept(); // 3. Get input stream and receive data inputStream = accept.getInputStream(); // Solve the problem of Chinese character garbled code in byte stream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[5]; int len; while ((len = inputStream.read(buffer)) != -1) { byteArrayOutputStream.write(buffer, 0, len); } System.out.println(byteArrayOutputStream.toString()); // You can get the relevant information of the client System.out.println(accept.getInetAddress().getHostAddress()); } catch (IOException e) { e.printStackTrace(); } finally { // Action to close a resource } } public void client() { Socket socket = null; OutputStream outputStream = null; try { String msg = "The sword of the river comes from the sky"; // 1. Create a Socket object to indicate the IP address and port number of the server InetAddress localHost = InetAddress.getLocalHost(); socket = new Socket(localHost, 11223); // 2. Obtain output stream and send data outputStream = socket.getOutputStream(); outputStream.write(msg.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { // Action to close a resource } }
Example 2: the client sends the file to the server, and the server returns "received successfully" to the client
// Streams should be handled with try catch finally public void server() throws Exception { ServerSocket serverSocket = new ServerSocket(12589); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); FileOutputStream fos = new FileOutputStream("xin1.jpg"); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } // The server gives feedback to the client OutputStream os = socket.getOutputStream(); os.write("Sent successfully".getBytes()); os.close(); fos.close(); is.close(); socket.close(); serverSocket.close(); } public void client() throws Exception { Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 12589); OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream("xin.jpg"); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } // Turn off data output socket.shutdownOutput(); InputStream is = socket.getInputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer1 = new byte[5]; int len1; while ((len1 = is.read(buffer1)) != -1) { byteArrayOutputStream.write(buffer1, 0, len1); } System.out.println(byteArrayOutputStream); byteArrayOutputStream.close(); is.close(); fis.close(); os.close(); socket.close(); }
4.UDP network programming
- Classes datagram socket and datagram packet implement network programs based on UDP protocol
- UDP datagram is sent and received through datagram socket. The system does not guarantee that UDP datagram can be safely sent to the destination, nor can it determine when it can arrive
- Datagram packet object encapsulates UDP datagram, which contains the IP address and port number of the sender and the IP address and port number of the receiver
- Each datagram in UDP protocol gives complete address information, so there is no need to establish a connection between the sender and the receiver
Example: the sender sends data, and the receiver receives the data and displays the data on the console
public void send() throws Exception { // Get socket DatagramSocket socket = new DatagramSocket(); // Encapsulate a datagram String msg = "The sword of the river comes from the sky"; byte[] data = msg.getBytes(); InetAddress address = InetAddress.getByName("127.0.0.1"); DatagramPacket packet = new DatagramPacket(data, 0, data.length, address, 12580); // Send datagram socket.send(packet); // close socket.close(); } public void receiver() throws Exception { // Get socket DatagramSocket socket = new DatagramSocket(12580); // Create datagram byte[] data = new byte[1024]; DatagramPacket packet = new DatagramPacket(data, 0, data.length); // receive data socket.receive(packet); System.out.println(new String(packet.getData(), 0, packet.getLength())); // close socket.close(); }
5.URL programming
- URL: uniform resource locator, which represents the address of a resource on the Internet
- It is a specific URI, that is, the URL can be used to identify a resource, and also indicates how to locate the resource
- Through the URL, we can access various network resources on the Internet. The browser can find the corresponding files or other resources on the network by parsing the given URL
- Basic structure of URL: < transport protocol > / / < host name >: < port number > / < file name > # fragment name? parameter list
public void test() throws Exception { URL url = new URL("http://localhost:8080/examples/xin.jpg?username=dudu"); System.out.println(url.getProtocol()); // Get Protocol http System.out.println(url.getHost()); // Get hostname localhost System.out.println(url.getPort()); // Get port number 8080 System.out.println(url.getPath()); // Get the path / examples / Xin jpg System.out.println(url.getFile()); // Get the file name / examples / Xin jpg? username=dudu System.out.println(url.getQuery()); // Get parameter username=dudu }
Realize data download of Tomcat server
public void test() throws Exception { URL url = new URL("http://localhost:8080/examples/xin.jpg"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream is = connection.getInputStream(); FileOutputStream fos = new FileOutputStream("xin2.jpg"); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { fos.write(buffer, 0, len); } System.out.println("Download complete"); fos.close(); is.close(); connection.disconnect(); }