Java network programming

Posted by BarmyArmy on Sat, 25 Dec 2021 02:06:55 +0100

Introduction to network programming

software structure

C/S structure: the full name is Client/Server structure, which refers to client and server structure. Common programs include QQ, Xunlei and other software.

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.

Network communication protocol

Network communication protocol:

Communication protocol is the rules that must be observed by computers. Only by observing these rules can computers communicate with each other. This is just like a car driving on the road must abide by the traffic rules. The protocol has unified provisions on the data transmission format, transmission rate and transmission steps. Both communication parties must abide by them at the same time and finally complete the data exchange.

TCP/IP protocol:
Transmission control protocol / Internet protocol is the most basic and extensive protocol on the Internet. It defines standards for how computers connect to the Internet and how data is transmitted between them. It contains a series of protocols for processing data communication, and adopts a 4-layer layered model. Each layer calls the protocols provided by its next layer to complete its own requirements.

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: TCP and UDP.

TCP: transmission control protocol. TCP protocol is a connection oriented communication protocol, that is, before transmitting data, establish a logical connection between the sender and the receiver, and then transmit data. It provides reliable error free data transmission between two computers.

Three handshakes: in TCP protocol, three interactions between the client and the server in the preparation stage of sending data to ensure the reliability of the connection.
The first handshake, the client sends a connection request to the server and waits for the server to confirm.
In the second handshake, the server sends back a response to the client to notify the client that it has received the connection request.

For the third handshake, the client sends a confirmation message to the server again to confirm the connection.
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.
The whole interaction process is shown in the figure below.

UDP: user datagram protocol. UDP protocol is a connectionless protocol. When transmitting data, there is no need to establish a connection. No matter whether the other side service is started or not, the data, data source and destination are directly encapsulated in data packets and sent directly. The size of each packet is limited to 64k. It is an unreliable protocol, because there is no connection, so the transmission speed is fast, but it is easy to lose data. In daily applications, such as video conference, QQ chat, etc.

Three elements of network programming

agreement

Rules that must be observed in computer network communication

IP address

IP address: refers to Internet Protocol Address, commonly known as IP. IP address is used to make a unique number for computer equipment in a network. If we compare "personal computer" to "a telephone", then "IP address" is equivalent to "telephone number".

IP address classification:

IPv4: a 32-bit binary number, usually divided into 4 bytes, expressed in the form of a.b.c.d, such as 192.168 65.100 . Where a, B, C and D are decimal integers between 0 and 255, it can represent 4.2 billion at most.

IPv6: due to the vigorous development of the Internet, the demand for IP address is increasing, but the limited network address resources make the allocation of IP more and more tense. Data show that the global IPv4 address was allocated in February 2011.

In order to expand the address space, it is proposed to redefine the address space through IPv6. The 128 bit address length is adopted, a group of 16 bytes is divided into 8 groups of hexadecimal numbers, expressed as ABCD:EF01:2345:6789:ABCD:EF01:2345:6789. It is said that it can compile a network address for every grain of sand in the world, which solves the problem of insufficient network address resources.

Common commands:

To view the local IP address, enter:

ipconfig

Check whether the network is connected. Enter:

ping blank IP address
ping 220.181. 57.216 (example)

Special IP address:

Local IP address: 127.0 0.1 , localhost .

Port number

If the IP address can uniquely identify the device in the network, the port number can uniquely identify the process (application) in the device.

Port number:

An integer represented by two bytes. Its value range is 065535. Among them, the port numbers between 01023 are used for some well-known network services and applications, and ordinary applications need to use port numbers above 1024. If the port number is occupied by another service or application, the current program will fail to start.

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.

TCP communication program

summary

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:

  1. The server program needs to be started in advance and wait for the connection of the client.
  2. The client actively connects to the server and can communicate only after the connection is successful. The server cannot actively connect to the client.

In Java, two classes are provided to implement TCP communication programs:

  1. Client: Java net. The Socket class represents. Create a Socket object, send a connection request to the server, and the server responds to the request. The two establish a connection and start communication.
  2. Server: Java net. The ServerSocket class represents. Creating a ServerSocket object is equivalent to starting a service and waiting for the client to connect.

Socket class

Socket class: this class implements client socket. Socket refers to the endpoint of communication between two devices.

Construction method:

public Socket(String host, int port): creates a socket object and connects it to the specified port number on the specified host. If the specified host is null, it is equivalent to that the specified address is the loopback address.

Example:

Socket client = new Socket("127.0.0.1", 6666);

Member method:

public InputStream getInputStream(): returns the input stream of this socket.

If this socket has an associated channel, all operations of the generated InputStream are also associated with that channel.
Closing the generated InputStream will also close the relevant Socket.

public OutputStream getOutputStream(): returns the output stream of this socket.

If this socket has an associated channel, all operations of the generated OutputStream are also associated with the channel.
Closing the generated OutputStream will also close the relevant Socket.

public void close(): close this socket.

Once a socket is closed, it can no longer be used.
Closing this socket will also close the associated InputStream and OutputStream.

public void shutdownOutput() :

Disable the output stream for this socket.
Any previously written data will be sent, and then the output stream will be terminated.

ServerSocket class

ServerSocket class: this class implements the server socket, which waits for requests through the network.

Construction method:
public ServerSocket(int port): when creating a ServerSocket object using this construction method, you can bind it to a specified port number. The parameter port is the port number.

For example:

ServerSocket server = new ServerSocket(1234);

Member method:
public Socket accept(): listen and accept the connection, and return a new Socket object for communication with the client. This method blocks until a connection is established.

Simple TCP network program

TCP communication analysis diagram:

  1. Start the server, create a ServerSocket object, and wait for the connection.
  2. [Client] start, create Socket object and request connection.
  3. [server] receives the connection, calls the accept method, and returns a Socket object.
  4. [Client] Socket object, obtain OutputStream and write data to the server.
  5. [server] socket object, get InputStream and read the data sent by the client.
  6. [server] Socket object, obtain OutputStream and write back data to the client.
  7. [Client] socket object, get InputStream, parse and write back data.
  8. [Client] release resources and disconnect.


Client sends data to server:
Server implementation:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(8848);

        Socket socket= serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        byte bytes[]=new byte[1024];
        int len=inputStream.read(bytes);

        System.out.println(new String(bytes,0,len));

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("Yes, thank you".getBytes());
        serverSocket.close();
    }
}

Client implementation:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class client {
    public static void main(String[] args) throws IOException {

        Socket socket=new Socket("127.0.0.1",8848);

        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("Hello, server, I'm the client".getBytes());

        InputStream inputStream = socket.getInputStream();

        byte bytes[]=new byte[1024];
        int len=inputStream.read(bytes);

        System.out.println(new String(bytes,0,len));

        socket.close();
    }
}

Comprehensive case

File upload analysis

  1. [Client] input stream to read file data from hard disk into program.
  2. [Client] output the stream and write out the file data to the server.
  3. [server] input the stream and read the file data to the server program.
  4. [server] output stream, write out file data to the server hard disk.


client:

import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Fileclient {
    public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream=new FileInputStream("C:\\Users\\Administrator\\Desktop\\1.jpg");
        Socket socket=new Socket("127.0.0.1",6666);
        OutputStream outputStream = socket.getOutputStream();
        int len=0;
        byte bytes[]=new byte[1024];
        while ((len=fileInputStream.read(bytes))!=-1)
        {
            outputStream.write(bytes);
        }
        socket.close();
    }
}

Server side:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Fileserver{
    public static void main(String[] args) throws Exception {
        ServerSocket serverSocket=new ServerSocket(6666);

        while (true) {
            File file = new File("C:\\");
            if (!file.exists())
                file.mkdirs();

            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            String fileName = "itcast" + System.currentTimeMillis() +new Random().nextInt(999999) + ".jpg";

            FileOutputStream fileOutputStream = new FileOutputStream(file.getAbsoluteFile() + fileName);
            int len = 0;
            byte bytes[] = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        }
    }
}

Impersonate B\S server

Simulate the web server, use the browser to access the server-side program written by yourself to view the web page effect.
First, put the network file under the idea project

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class BSserver {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(8000);

        while (true)
        {
            Socket socket=serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream inputStream=socket.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

                        String line=bufferedReader.readLine();
                        System.out.println(line);
                        String arr[]=line.split(" ");
                        String htmlpath=arr[1].substring(10);
                        System.out.println(line);

                        FileInputStream fileInputStream=new FileInputStream(htmlpath);

                        OutputStream os = socket.getOutputStream();
                        os.write("HTTP/1.1 200 OK\r\n".getBytes());
                        os.write("Content-Type:text/html\r\n".getBytes());
                        // You must write a blank line, otherwise the browser will not parse it
                        os.write("\r\n".getBytes());
                        int len = 0;
                        byte[] bytes = new byte[1024];
                        while((len = fileInputStream.read(bytes))!=-1){
                            os.write(bytes,0,len);
                        }
                        fileInputStream.close();
                        socket.close();
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}



(no picture)

Topics: Java computer networks Network Protocol