Express management console simple version - add multithreading and network programming (full version with complete source code) (Java)

For the array storage version, please refer to the following article: Express management console simple version - array storage Version (Java)

For the List collection storage version, please refer to the following article: Express management console simple version - List collection storage Version (Java)

For Map collection storage version, please refer to the following article: Express management console simple version - Map collection storage Version (Java)

Using IO technology to realize data storage based on Map collection storage version, please refer to the article: Express management console easy version - use of IO stream (Java)

  • The array storage version uses a two-dimensional array to store the express, and the express location corresponds to the two subscripts of the two-dimensional array

  • The List set storage version uses the List set to store the express

  • The Map set storage version uses the Map set to store express delivery. The advantage of using the Map set for storage is that Map is a key value pair, key is the express delivery order number, and value is the express object to ensure that the express delivery order number is unique

  • The use of IO stream is optimized based on the Map set storage version. The IO technology is used to store the express data in the file and read the data from the file. After the file stores the express information, the content of the file can be read every time the application is started, so as to realize the existence of program data all the time

  • With regard to multithreading and network programming, multithreading and network programming technology are added to realize the data interaction between the client and the server, and multithreading is used to make each user send a login request to the server, and the server will allocate a thread to process the request
    tips: This article only involves how to join multithreading and use network programming technology, not a complete console operation

Specific needs

  1. Realize the user login function based on network programming mode. Requirements:
    (1) Users include administrator and ordinary users for testing
    Administrator user name: admin, password: abc ordinary user name: user password: 123
    (2) The user initiates a login request from the client, and the client transmits the data to the server,
    Verified by the server. The server side saves the user data. If the user logs in successfully, it will be prompted that the login is successful
    The function module is displayed, and the login failure prompt: the user name or password is incorrect
  2. Based on the previous exercise, understand the concepts of client and server. The client is used to obtain user information, and the server is used for data storage and logical judgment
    On the basis of network programming, the multithreading mode is enabled on the server side. After each user sends a login request to the server, the server side allocates a thread to process the request, so as to realize the user login under the multithreading mode on the server side

Knowledge points involved

  1. object-oriented
  2. aggregate
  3. IO
  4. Multithreading
  5. Network programming

Idea and code implementation

The following code only involves the addition of multithreading and network programming to realize user login and interface display, so the code is incomplete

1, Custom exception

Create an exception package and create a new class OutNumberBoundException

OutNumberBoundException

public class OutNumberBoundException extends Throwable {
    public OutNumberBoundException(String s) {
        super(s);
    }
}

2, Tool kit

Create a util package and create a new class IOUtil

IOUtil

File reading and writing tool classes, so static is recommended for all methods

  • Read data from the specified file
public static Object readFile(String fileName) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(fileName);//Specify file
        ObjectInputStream ois = new ObjectInputStream(fis);
        return ois.readObject();//Read data
    }
  • Write data to the specified file
 public static void writeFile(Object obj,String fileName) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileName);//Specify file
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);//Write data obj
    }

3, Object

Create a pojo package and create a new Express class

Express

  • Define properties and set and get values with setter s and getter s
	private String number;//courier number
    private String company;//company
    private int code;//Pick up code
    private int x;
    private int y;
    
	 /**
     * Use setter s and getter s to set and get values
     */
    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
  • Define nonparametric and full parameter construction methods
/**
     * Define parameterless construction method
     */
    public Express() {
    }

    /**
     * Define full parameter construction method
     */
    public Express(String number, String company, int code, int x, int y) {
        this.number = number;
        this.company = company;
        this.code = code;
        this.x = x;
        this.y = y;
    }
  • Override toString to convert information to a string
    /**
     * toString Convert information to string form
     */
    @Override
    public String toString() {
        return "Express information[" +
                "courier number:" + getNumber() + ' ' +
                ", Courier Services Company:" + getCompany() + ' ' +
                ", Pick up code:" + getCode() + " , In the first" + (getX() + 1) + "Line number" + (getY() + 1) + "Column cabinet" +
                ']';
    }

4, Data processing

Create a Dao package and create a new Dao class

Dao

  • Create files and initialize data
    public static final String FILE_NAME = "Express information.txt";
    
    //Static code block
    static {
        File file = new File(FILE_NAME);
        if (!file.exists()){//If the file does not exist, create the file
            try {
                if (file.createNewFile()){//Create a file named FILE_NAME file
                    System.out.println("The project is started for the first time, and the saved file is created successfully!");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    //Initialization data
    public Dao() {
        //Read data from file
        try {
            Object obj = IOUtil.readFile(FILE_NAME);
            if (obj!=null && obj instanceof List){
                expressList = (List<Express>) obj;
            }
        }catch (IOException | ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }
  • Add express
    public static Express add(Express express) throws Exception {
        Random random = new Random();
        if (expressList.size() == 100) {
            System.out.println("The express cabinet is full!");
            return null;
        }
        int x, y;
        do {
            x = random.nextInt(10);
            y = random.nextInt(10);
        } while (isExist(x, y));

        int code;
        do {
            code = random.nextInt(900000) + 100000;
        } while (isExistCode(code));
        express.setCode(code);
        express.setX(x);
        express.setY(y);
        expressList.add(express);
        IOUtil.writeFile(expressList,FILE_NAME);//Update data in document
        return express;
    }

  • Judge whether express delivery already exists in the current location
    public static boolean isExist(int x, int y) {
        for (Express express : expressList) {
            if (express.getX() == x && express.getY() == y) {
                return true;
            }
        }
        return false;
    }
  • Judge whether the randomly generated pick-up code exists
    public static boolean isExistCode(int code) {
        for (Express express : expressList) {
            if (express.getCode() == code) {
                return true;
            }
        }
        return false;
    }
  • Delete Express
    public static boolean delete(String number) throws Exception {
        int index = findByNumber(number);
        if (index == -1) {
            return false;
        }
        expressList.remove(index);//Delete express delivery
        IOUtil.writeFile(expressList,FILE_NAME);
        return true;
    }
  • Query express delivery according to express delivery number
    public static int findByNumber(String number) {
        int i = 0;
        for (Express express : expressList) {
            if (number.equals(express.getNumber())) {
                return i;
            }
            i++;
        }
        return -1;
    }
  • Update Express
    public static boolean update(String number, Express newExpress) throws Exception {
        int index = findByNumber(number);
        if (index == -1) {
            System.out.println("Express does not exist!");
            return false;
        }
        Express express1 = expressList.get(index);
        express1.setNumber(newExpress.getNumber());
        express1.setCompany(newExpress.getCompany());
        IOUtil.writeFile(expressList,FILE_NAME);//Data join
        return true;
    }
  • Get all express information
    public static List<Express> getExpressList() {
        return expressList;
    }
  • Pick up express
    public Express findByCodeAndDelete(int code) throws Exception {
        Express express = findExpressByCode(code);
        if (express!=null){
            if (delete(express.getNumber())){
                return express;
            }
        }
        return null;
    }
  • Find express by picking up the piece code
    public static Express findExpressByCode(int code){
        for (int i = 0;i<expressList.size();i++) {
            if (expressList.get(i).getCode() == code){
                return expressList.get(i);
            }
        }
        return null;
    }

5, C/S network programming

  • It is mainly responsible for the interaction between the server and the client

Create a socket package and create new classes Server and Client

Server server

Create the Server object in main and call the start method

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

Next, write the start method to start the server:

First create the server

	//Port number
    private final int PORT = 10086; 
    
    //Create a server
    private ServerSocket server; 

1. Create a start method to build and run the server and connect the client

  • Wait for the client to connect after entering the server
    Use the while loop to realize multiple connections of users
	server = new ServerSocket(PORT);//The port number is passed in to the server
	System.out.println("The server is ready! Service port:" + PORT);
	//Waiting for the client to connect
	while (true) {//Realize multi-user connection and use the while loop
		Socket client = server.accept();//Clients connected to the server
        System.out.println("client" + client.hashCode() + "Connection succeeded");//Different hashcode s represent different objects
    }
  • Join multithreading and use anonymous inner classes
	//A separate thread is opened for each client to process requests
	new Thread(new Runnable() {
		@Override
		public void run() {
        //The client's request accepts the client's request to read data -- after processing, give the result to the client -- write data to the client
        	try {
            	init(client);//The user's methods include serialization and deserialization
            } catch (IOException|Exception e) {
            	e.printStackTrace();
            } 
        }
     }).start();

The complete code of the start() method is as follows:

    //The method of starting a thread server
    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    server = new ServerSocket(PORT);//The port number is passed in to the server
                    System.out.println("The server is ready! Service port:" + PORT);
                    //Waiting for the client to connect
                    while (true) {//Realize multi-user connection and use the while loop
                        Socket client = server.accept();//Clients connected to the server
                        System.out.println("client" + client.hashCode() + "Connection succeeded");//Different hashcode s represent different objects
                        //A separate thread is opened for each client to process requests
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //The client's request accepts the client's request to read data -- after processing, give the result to the client -- write data to the client
                                try {
                                    init(client);//The user's methods include serialization and deserialization
                                } catch (IOException|Exception  e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

2. Write the init method in the task run to realize the interaction with the client data

  • Receive message
        InputStream is = null;
        ObjectInputStream in = null;
  • Send a message
        OutputStream os = null;
        ObjectOutputStream out = null;
  • Get stream object
		is = client.getInputStream();
    	os = client.getOutputStream();
   		out = new ObjectOutputStream(os);
    	in = new ObjectInputStream(is);
  • Enter the system
       System.out.println("User's request type" + flag + "thread " + Thread.currentThread().getName() + "Serve you!");
  • Get the specific operation of the user
		String flag = in.readUTF();
		System.out.println(flag);
    • Add express
                    //Get parameters published by the client
                    Express express = (Express) in.readObject();
                    express = dao.add(express);
                    out.writeObject(express);
    • Delete Express
                    String number = in.readUTF();
                    boolean res = dao.delete(number);
                    out.writeObject(res);
    • Modify Express
                    String number =in.readUTF();//Old data
                    Express newExpress = (Express) in.readObject();
                    boolean res = dao.update(number, newExpress);
    • Print all express
                	//Print the current express storage information on the server side
                    System.out.println("-----------------------------------implement findadll");
                    List<Express> expressList = dao.getExpressList();
                    //Get the processing result and return it to the client to write data
                    if (expressList != null && expressList.size() != 0) {
                        System.out.println("----------------The current express information is as follows, ready to send to the client---------------------------");
                        for (Express express : expressList) {//ergodic
                            System.out.println("--" + express);
                        }
                        out.reset();
                        out.writeObject(expressList);
                        System.out.println("Sending succeeded!");
                    } else
                        out.writeObject("There is no express in the express cabinet for the time being");
                        out.flush();
    • Take parts
                    Integer code = in.readInt();
                    Express res = dao.findByCodeAndDelete(code);
                    System.out.println("res:"+res);
                    out.writeObject(res);
  • Close flow
		if (in != null) {
			in.close();
			}
        if (out != null) {
            out.close();
        }

The complete code of init method is as follows:

	//Accept the client's request to read data -- send the result to the client after processing -- write data to the client
    public void init(Socket client) throws Exception {
        OutputStream os = null;
        ObjectOutputStream out = null;
        InputStream is = null;
        ObjectInputStream in = null;

        //Get stream object
        try {
            is = client.getInputStream();
            os = client.getOutputStream();
            out = new ObjectOutputStream(os);
            in = new ObjectInputStream(is);
            //Gets the type of request sent by the client
            while (true) {
                System.out.println("User's request type" + flag + "thread " + Thread.currentThread().getName() + "Serve you!");
                
                String flag = in.readUTF();
                System.out.println(flag);
                if ("printAll".equals(flag)) {
                	//Print the current express storage information on the server side
                    System.out.println("-----------------------------------implement findadll");
                    List<Express> expressList = dao.getExpressList();
                    //Get the processing result and return it to the client to write data
                    if (expressList != null && expressList.size() != 0) {
                        System.out.println("----------------The current express information is as follows, ready to send to the client---------------------------");
                        for (Express express : expressList) {//ergodic
                            System.out.println("--" + express);
                        }
                        out.reset();
                        out.writeObject(expressList);
                        System.out.println("Sending succeeded!");
                    } else
                        out.writeObject("There is no express in the express cabinet for the time being");
                        out.flush();
                    continue;
                } else if ("insert".equals(flag)) {
                    //Get parameters published by the client
                    Express express = (Express) in.readObject();
                    express = dao.add(express);
                    out.writeObject(express);
                    continue;
                } else if ("update".equals(flag)) {
                    String number =in.readUTF();//Old data
                    Express newExpress = (Express) in.readObject();
                    boolean res = dao.update(number, newExpress);
                    out.writeObject(res);
                    continue;
                } else if ("delete".equals(flag)) {
                    String number = in.readUTF();
                    boolean res = dao.delete(number);
                    out.writeObject(res);
                    continue;
                } else if ("findByCode".equals(flag)) {//The fetching part is queried first and then deleted
                    Integer code = in.readInt();
                    Express res = dao.findByCodeAndDelete(code);
                    System.out.println("res:"+res);
                    out.writeObject(res);
                    continue;
                } else {
                    out.writeObject("Your request cannot be processed by the server for the time being");
                    continue;
                }
            }//end while
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }//end void

Client client

Create a Client object in main and call the start method to connect the user to the server

    public static void main(String[] args) {
        Client c = new Client();
        c.start();
    }

First create the client

    private final int PORT = 10086;//The port number that the client will link to
    
    private Socket client;//client

1. Create the start method, run the client and connect to the server

  • Receive message
        InputStream is = null;
        ObjectInputStream in = null;
  • Send a message
        OutputStream os = null;
        ObjectOutputStream out = null;
  • Connect server
            do {
                if (client == null || client.isClosed()) {
                    client = new Socket("127.8.0.1", PORT);
                    in = client.getInputStream();
                    out = client.getOutputStream();
                    objectOutputStream = new ObjectOutputStream(out);
                    objectInputStream = new ObjectInputStream(in);
                    System.out.println("The client successfully connected to the server!");
                }
            } while (mainMenu(objectInputStream, objectOutputStream) != 0);
  • Exit the system and close the flow
		if (objectInputStream != null) {
			objectInputStream.close();
		}
	    if (objectOutputStream != null) {
			objectOutputStream.close();
	    }
		if (client != null) {
			client.close();
		}

The complete method of start is as follows:

    //Method of client startup
    public void start() {
        OutputStream out = null;
        ObjectOutputStream objectOutputStream = null;
        InputStream in = null;
        ObjectInputStream objectInputStream = null;
        //Get stream object
        try {
            do {
                if (client == null || client.isClosed()) {
                    client = new Socket("127.8.0.1", PORT);
                    in = client.getInputStream();
                    out = client.getOutputStream();
                    objectOutputStream = new ObjectOutputStream(out);
                    objectInputStream = new ObjectInputStream(in);
                    System.out.println("The client successfully connected to the server!");
                }
            } while (mainMenu(objectInputStream, objectOutputStream) != 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutNumberBoundException e) {
            e.printStackTrace();
        } finally {//Close flow
            try {
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }//end finally
    }//end void start

2. Main menu

    public static int mainMenu(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception {
        int mainNum = 0;
        do{
            System.out.println("----------Welcome to express management system----------");
            System.out.println("Please select your identity:");
            System.out.println("1.administrators");
            System.out.println("2.Ordinary users");
            System.out.println("0.sign out");
            String s = input.nextLine();
            try{
                mainNum = validNum(s,0,2);
                break;
            }catch(NumberFormatException | OutNumberBoundException e){
                System.out.println(e.getMessage());
            }
        }while(true);
        switch(mainNum){
            case 0://End use
                System.out.println("Thank you for using the express management system!");
                break ;
            case 1://Enter the administrator platform
                managerPlatform(in,out);
                break ;
            case 2://Enter user platform
                userPlatform(in,out);
                break ;
        }
        return mainNum;
    }//end mainMenu()
  • Judge whether the input is a valid number
    private static int validNum(String s,int begin,int end) throws NumberFormatException, OutNumberBoundException {
        try{
            int num = Integer.parseInt(s);
            if (num < begin || num > end){
                throw new OutNumberBoundException("The range of numbers must be" + begin + "and" + end +"between");
            }
            return num;
        }catch(NumberFormatException | OutNumberBoundException e){
            throw new NumberFormatException("The input must be a number!");
        }
    }

2.1 administrator interface

    public static void managerPlatform(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception{
        w:while(true){
            int managerNum = 0;
            do{
                System.out.println("Dear administrator, Hello!");
                System.out.println("Please select what you want to do:");
                System.out.println("1.Enter Express");
                System.out.println("2.Delete Express");
                System.out.println("3.Modify Express");
                System.out.println("4.View all express");
                System.out.println("0.Return to the previous interface");
                String s = input.nextLine();
                try{
                    managerNum = validNum(s,0,4);
                    break;
                }catch(NumberFormatException | OutNumberBoundException e){
                    System.out.println(e.getMessage());
                }
            }while(true);
            switch(managerNum){
                case 0:{//Return to previous page
                    return;
                }
                case 1:{//1. Enter Express
                    insert(in,out);
                }
                break w;
                case 2:{//2. Delete Express
                    delete(in,out);
                }
                break w;
                case 3:{//3. Modify Express
                    update(in,out);
                }
                break w;
                case 4:{//4. View all express
                    printAll(in,out);
                }
                break w;
            }// end switch
        }//end while
    }//end managerPlatform

  • Add express
    private static void insert(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("---------Deposit Express----------");
        Express express = new Express();
        System.out.print("Please enter the courier number:");
        express.setNumber(input.nextLine());
        System.out.print("Please enter the courier company:");
        express.setCompany(input.nextLine());
        //The current express delivery order No. does not exist, please save it
        if(Server.dao.findByNumber(express.getNumber()) == -1){
            try {
                out.writeUTF("insert");
                out.writeObject(express);
                out.flush();
                //Accept the server-side response - read data
                Object object = in.readObject();
                if (object instanceof Express) {
                    express = (Express) object;
                    System.out.println("Successfully added! Express at" + (express.getX() + 1) + "Row, No" + (express.getY() + 1) + "column");
                } else {
                    System.out.println("Add failed" + object);
                }
            } catch (Exception exception) {
                System.out.println("System exception, failed to add!");
                System.out.println(exception.getMessage());
            }
        }else{
            System.out.println("The express order No. already exists! Failed to add express!");
        }
    }
  • Delete Express
    private static void delete(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("Delete Express");
        System.out.print("Please enter the express order number to delete:");
        String number = input.nextLine();
        int exist = Server.dao.findByNumber(number);
        if (exist == -1) {
            System.out.println("Express does not exist!");
        } else {
            int deleteNum;
            do {
                System.out.println("Delete?");
                System.out.println("1.confirm deletion");
                System.out.println("0.Cancel operation");
                String s = input.nextLine();
                deleteNum = -1;
                try {
                    deleteNum = validNum(s, 0, 1);
                    break;
                } catch (NumberFormatException | OutNumberBoundException e) {
                    System.out.println(e.getMessage());
                }
            } while (true);
            if (deleteNum == 0) {
                System.out.println("Cancel deletion succeeded!");
            } else {
                try {
                    out.writeUTF("delete");
                    out.writeUTF(number);
                    out.flush();
                    Object obj = in.readObject();
                    if (obj instanceof Boolean) {
                        boolean res = (boolean) obj;
                        if (res == true) {
                            System.out.println("Delete succeeded");
                        } else {
                            System.out.println("Deletion failed");
                        }
                    } else {
                        System.out.println("Deletion failed!!!!!!");
                    }
                } catch (Exception e) {
                    System.out.println("System exception, deletion failed!");
                    System.out.println(e.getMessage());
                }
            }// end else  option of delete
        }//end else express exist
    }//end method
  • Modify Express
    private static void update(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("---------Modify Express-----------");
        System.out.print("Please enter the courier number to be modified:");
        String number = input.nextLine();
        int exist = Server.dao.findByNumber(number);
        if(exist == -1){
            System.out.println("Express does not exist!");
        }else{
            Express newExpress = new Express();
            System.out.print("Please enter a new courier number:");
            newExpress.setNumber(input.nextLine());
            System.out.print("Please enter a new company name:");
            newExpress.setCompany(input.nextLine());
            try {
                out.writeUTF("update");
                out.flush();
                out.writeUTF(number);
                out.flush();
                out.writeObject(newExpress);
                out.flush();
                Object obj = in.readObject();
                if (obj instanceof Boolean) {
                    boolean res = (boolean) obj;
                    if (res == true) {
                        System.out.println("Update succeeded!");
                    } else {
                        System.out.println("Update failed!");
                    }
                } else{
                    System.out.println("Update failed!!!!!!");
                }
            } catch (Exception e) {
                System.out.println("System exception,Update failed!");
                System.out.println(e.getMessage());
            }
        }// end else(option of exist then update)
    }//end update method
  • Print all express
    public static void printAll(ObjectInputStream in, ObjectOutputStream out) throws IOException, ClassNotFoundException {
        System.out.println("--------Current express storage---------");
        out.writeUTF("printAll");//Corresponding to the Server, the type of request sent to the Server
        out.flush();
        Object obj = in.readObject();
        if (obj instanceof List) {
            List<Express> expressList = (List<Express>) obj;//Strong rotation
            for (Express express : expressList) {//Traversal output
                System.out.println(express);
            }
        }else {
            System.out.println(obj);
        }
    }

2.2 user interface

  • Take parts
    public static void userPlatform(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception {
        int code = -1;
        do {
            System.out.print("Please enter the pickup Code:");
            String s = input.nextLine();
            try {
                code = validNum(s, 100000, 999999);
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
                System.out.println(e.getMessage());
            }
        } while (true);
        out.writeUTF("findByCode");
        out.writeInt(code);
        out.flush();
        Object obj = in.readObject();
        if (obj instanceof Express) {
            Express e = (Express) obj;
            System.out.println("Express information:" + e);
            System.out.println("Your express is stored in the second section of the express cabinet" + (e.getX() + 1) + "Row,The first" + (e.getY() + 1) + "column,Have a nice pick-up~");

        } else {
            System.out.println("Express doesn't exist, pick-up failed!");
        }
    }

Complete code

1, Custom exception

OutNumberBoundException

public class OutNumberBoundException extends Throwable {
    public OutNumberBoundException(String s) {
        super(s);
    }
}

2, Tool kit

IOUtil

/**
 * File reading and writing technology
 *
 */
public class IOUtil {
    /**
     * Reads data from the specified file
     * Reader
     * InputStream
     */
    public static Object readFile(String fileName) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(fileName);//Specify file
        ObjectInputStream ois = new ObjectInputStream(fis);
        return ois.readObject();//Read data
    }

    /**
     * Write data to the specified file
     * Writer
     * OutputStream
     */
    public static void writeFile(Object obj,String fileName) throws IOException {
        FileOutputStream fos = new FileOutputStream(fileName);//Specify file
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);//Write data obj
    }

}

3, Object

Express

public class Express implements Serializable {
    private String number;//courier number
    private String company;//company
    private int code;//Pick up code
    private int x;
    private int y;

    /**
     * Define parameterless construction method
     */
    public Express() {
    }

    /**
     * Define full parameter construction method
     */
    public Express(String number, String company, int code, int x, int y) {
        this.number = number;
        this.company = company;
        this.code = code;
        this.x = x;
        this.y = y;
    }

    /**
     * Use setter s and getter s to set and get values
     */
    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    /**
     * toString Convert information to string form
     */
    @Override
    public String toString() {
        return "Express information[" +
                "courier number:" + getNumber() + ' ' +
                ", Courier Services Company:" + getCompany() + ' ' +
                ", Pick up code:" + getCode() + " , In the first" + (getX() + 1) + "Line number" + (getY() + 1) + "Column cabinet" +
                ']';
    }
}

4, Data processing

Dao

public class Dao {
    //Initial setting of linked list
    private static List<Express> expressList = new ArrayList<>(100);
    //Store the file name of the courier
    public static final String FILE_NAME = "Express information.txt";

    //Static code block
    static {
        File file = new File(FILE_NAME);
        if (!file.exists()){//If the file does not exist, create the file
            try {
                if (file.createNewFile()){//Create a file named FILE_NAME file
                    System.out.println("The project is started for the first time, and the saved file is created successfully!");
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    
    //Initialization data
    public Dao() {
        //Read data from file
        try {
            Object obj = IOUtil.readFile(FILE_NAME);
            if (obj!=null && obj instanceof List){
                expressList = (List<Express>) obj;
            }
        }catch (IOException | ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
    }


    /**
     * Get all the information of Express
     * @return
     */
    public static List<Express> getExpressList() {
        return expressList;
    }


    /**
     * Add express
     * @param express
     * @return
     * @throws Exception
     */
    public static Express add(Express express) throws Exception {
        Random random = new Random();
        if (expressList.size() == 100) {
            System.out.println("The express cabinet is full!");
            return null;
        }
        int x, y;
        do {
            x = random.nextInt(10);
            y = random.nextInt(10);
        } while (isExist(x, y));

        int code;
        do {
            code = random.nextInt(900000) + 100000;
        } while (isExistCode(code));
        express.setCode(code);
        express.setX(x);
        express.setY(y);
        expressList.add(express);
        IOUtil.writeFile(expressList,FILE_NAME);//Update data in document
        return express;
    }


    /**
     * When adding express, judge whether express already exists in the current location
     * @param x
     * @param y
     * @return
     */
    public static boolean isExist(int x, int y) {
        for (Express express : expressList) {
            if (express.getX() == x && express.getY() == y) {
                return true;
            }
        }
        return false;
    }

    /**
     * Judge whether the pick-up code already exists
     * @param code
     * @return
     */
    public static boolean isExistCode(int code) {
        for (Express express : expressList) {
            if (express.getCode() == code) {
                return true;
            }
        }
        return false;
    }

    /**
     * Find the express according to the express document number. If it does not exist, return - 1
     * @param number
     * @return
     */
    public static int findByNumber(String number) {
        int i = 0;
        for (Express express : expressList) {
            if (number.equals(express.getNumber())) {
                return i;
            }
            i++;
        }
        return -1;
    }


    /**
     * Delete Express
     * @param number
     * @return
     * @throws Exception
     */
    public static boolean delete(String number) throws Exception {
        int index = findByNumber(number);
        if (index == -1) {
            return false;
        }
        expressList.remove(index);//Delete express delivery
        IOUtil.writeFile(expressList,FILE_NAME);
        return true;
    }


    /**
     * Update Express
     * @param number
     * @param newExpress
     * @return
     * @throws Exception
     */
    public static boolean update(String number, Express newExpress) throws Exception {
        int index = findByNumber(number);
        if (index == -1) {
            System.out.println("Express does not exist!");
            return false;
        }
        Express express1 = expressList.get(index);
        express1.setNumber(newExpress.getNumber());
        express1.setCompany(newExpress.getCompany());
        IOUtil.writeFile(expressList,FILE_NAME);//Data join
        return true;
    }

    /**
     * Find express by picking up the piece code
     * @param code
     * @return
     */
    public static Express findExpressByCode(int code){
        for (int i = 0;i<expressList.size();i++) {
            if (expressList.get(i).getCode() == code){
                return expressList.get(i);
            }
        }
        return null;
    }

    /**
     * Pick up, delete Express
     * @param code
     * @return
     * @throws IOException
     */
    public Express findByCodeAndDelete(int code) throws Exception {
        Express express = findExpressByCode(code);
        if (express!=null){
            if (delete(express.getNumber())){
                return express;
            }
        }
        return null;
    }
}

5, C/S network programming

Server

public class Server {
    public static Dao dao = new Dao();
    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private final int PORT = 10086; //Port number

    private ServerSocket server; //Set up a server

    //The method of starting a thread server
    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    server = new ServerSocket(PORT);//The port number is passed in to the server
                    System.out.println("The server is ready! Service port:" + PORT);
                    //Waiting for the client to connect
                    while (true) {//Realize multi-user connection and use the while loop
                        Socket client = server.accept();//Clients connected to the server
                        System.out.println("client" + client.hashCode() + "Connection succeeded");//Different hashcode s represent different objects
                        //A separate thread is opened for each client to process requests
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //The client's request accepts the client's request to read data -- after processing, give the result to the client -- write data to the client
                                try {
                                    init(client);//The user's methods include serialization and deserialization
                                } catch (IOException|Exception  e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

	//Accept the client's request to read data -- send the result to the client after processing -- write data to the client
    public void init(Socket client) throws Exception {
        OutputStream os = null;
        ObjectOutputStream out = null;
        InputStream is = null;
        ObjectInputStream in = null;

        //Get stream object
        try {
            is = client.getInputStream();
            os = client.getOutputStream();
            out = new ObjectOutputStream(os);
            in = new ObjectInputStream(is);
            //Gets the type of request sent by the client
            while (true) {
                System.out.println("User's request type" + flag + "thread " + Thread.currentThread().getName() + "Serve you!");
                
                String flag = in.readUTF();
                System.out.println(flag);
                if ("printAll".equals(flag)) {
                	//Print the current express storage information on the server side
                    System.out.println("-----------------------------------implement findadll");
                    List<Express> expressList = dao.getExpressList();
                    //Get the processing result and return it to the client to write data
                    if (expressList != null && expressList.size() != 0) {
                        System.out.println("----------------The current express information is as follows, ready to send to the client---------------------------");
                        for (Express express : expressList) {//ergodic
                            System.out.println("--" + express);
                        }
                        out.reset();
                        out.writeObject(expressList);
                        System.out.println("Sending succeeded!");
                    } else
                        out.writeObject("There is no express in the express cabinet for the time being");
                        out.flush();
                    continue;
                } else if ("insert".equals(flag)) {
                    //Get parameters published by the client
                    Express express = (Express) in.readObject();
                    express = dao.add(express);
                    out.writeObject(express);
                    continue;
                } else if ("update".equals(flag)) {
                    String number =in.readUTF();//Old data
                    Express newExpress = (Express) in.readObject();
                    boolean res = dao.update(number, newExpress);
                    out.writeObject(res);
                    continue;
                } else if ("delete".equals(flag)) {
                    String number = in.readUTF();
                    boolean res = dao.delete(number);
                    out.writeObject(res);
                    continue;
                } else if ("findByCode".equals(flag)) {//The fetching part is queried first and then deleted
                    Integer code = in.readInt();
                    Express res = dao.findByCodeAndDelete(code);
                    System.out.println("res:"+res);
                    out.writeObject(res);
                    continue;
                } else {
                    out.writeObject("Your request cannot be processed by the server for the time being");
                    continue;
                }
            }//end while
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }//end void

}

Client

public class Client {
    private static Scanner input = new Scanner(System.in);
    private Express express = new Express();
    private final int PORT = 10086;//The port number that the client will link to
    private Socket client;//client

    public static void main(String[] args) {
        Client c = new Client();
        c.start();
    }
  
    //Method of client startup
    public void start() {
        OutputStream out = null;
        ObjectOutputStream objectOutputStream = null;
        InputStream in = null;
        ObjectInputStream objectInputStream = null;
        //Get stream object
        try {
            do {
                if (client == null || client.isClosed()) {
                    client = new Socket("127.8.0.1", PORT);
                    in = client.getInputStream();
                    out = client.getOutputStream();
                    objectOutputStream = new ObjectOutputStream(out);
                    objectInputStream = new ObjectInputStream(in);
                    System.out.println("The client successfully connected to the server!");
                }
            } while (mainMenu(objectInputStream, objectOutputStream) != 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } catch (OutNumberBoundException e) {
            e.printStackTrace();
        } finally {//Close flow
            try {
                if (objectInputStream != null) {
                    objectInputStream.close();
                }
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }//end finally
    }//end void start
    
    /**
     * Main menu, system interface
     * @return
     */
    public static int mainMenu(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception {
        int mainNum = 0;
        do{
            System.out.println("----------Welcome to express management system----------");
            System.out.println("Please select your identity:");
            System.out.println("1.administrators");
            System.out.println("2.Ordinary users");
            System.out.println("0.sign out");
            String s = input.nextLine();
            try{
                mainNum = validNum(s,0,2);
                break;
            }catch(NumberFormatException | OutNumberBoundException e){
                System.out.println(e.getMessage());
            }
        }while(true);
        switch(mainNum){
            case 0://End use
                System.out.println("Thank you for using the express management system!");
                break ;
            case 1://Enter the administrator platform
                managerPlatform(in,out);
                break ;
            case 2://Enter user platform
                userPlatform(in,out);
                break ;
        }
        return mainNum;
    }//end mainMenu()

    /**
     * Judge whether the input is a number and within the valid range
     * @param s
     * @param begin
     * @param end
     * @return
     * @throws NumberFormatException
     */
    private static int validNum(String s,int begin,int end) throws NumberFormatException, OutNumberBoundException {
        try{
            int num = Integer.parseInt(s);
            if (num < begin || num > end){
                throw new OutNumberBoundException("The range of numbers must be" + begin + "and" + end +"between");
            }
            return num;
        }catch(NumberFormatException | OutNumberBoundException e){
            throw new NumberFormatException("The input must be a number!");
        }
    }


    /**
     * Administrator operation interface
     * @param in
     * @param out
     * @throws OutNumberBoundException
     * @throws Exception
     */
    public static void managerPlatform(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception{
        w:while(true){
            int managerNum = 0;
            do{
                System.out.println("Dear administrator, Hello!");
                System.out.println("Please select what you want to do:");
                System.out.println("1.Enter Express");
                System.out.println("2.Delete Express");
                System.out.println("3.Modify Express");
                System.out.println("4.View all express");
                System.out.println("0.Return to the previous interface");
                String s = input.nextLine();
                try{
                    managerNum = validNum(s,0,4);
                    break;
                }catch(NumberFormatException | OutNumberBoundException e){
                    System.out.println(e.getMessage());
                }
            }while(true);
            switch(managerNum){
                case 0:{//Return to previous page
                    return;
                }
                case 1:{//1. Enter Express
                    insert(in,out);
                }
                break w;
                case 2:{//2. Delete Express
                    delete(in,out);
                }
                break w;
                case 3:{//3. Modify Express
                    update(in,out);
                }
                break w;
                case 4:{//4. View all express
                    printAll(in,out);
                }
                break w;
            }// end switch
        }//end while
    }//end managerPlatform


    /**
     * Print all express
     * @param in
     * @param out
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void printAll(ObjectInputStream in, ObjectOutputStream out) throws IOException, ClassNotFoundException {
        System.out.println("--------Current express storage---------");
        out.writeUTF("printAll");//Corresponding to the Server, the type of request sent to the Server
        out.flush();
        Object obj = in.readObject();
        if (obj instanceof List) {
            List<Express> expressList = (List<Express>) obj;//Strong rotation
            for (Express express : expressList) {//Traversal output
                System.out.println(express);
            }
        }else {
            System.out.println(obj);
        }
    }


    /**
     * Add express
     * @param in
     * @param out
     */
    private static void insert(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("---------Deposit Express----------");
        Express express = new Express();
        System.out.print("Please enter the courier number:");
        express.setNumber(input.nextLine());
        System.out.print("Please enter the courier company:");
        express.setCompany(input.nextLine());
        //The current express delivery order No. does not exist, please save it
        if(Server.dao.findByNumber(express.getNumber()) == -1){
            try {
                out.writeUTF("insert");
                out.writeObject(express);
                out.flush();
                //Accept the server-side response - read data
                Object object = in.readObject();
                if (object instanceof Express) {
                    express = (Express) object;
                    System.out.println("Successfully added! Express at" + (express.getX() + 1) + "Row, No" + (express.getY() + 1) + "column");
                } else {
                    System.out.println("Add failed" + object);
                }
            } catch (Exception exception) {
                System.out.println("System exception, failed to add!");
                System.out.println(exception.getMessage());
            }
        }else{
            System.out.println("The express order No. already exists! Failed to add express!");
        }
    }


    /**
     * Delete Express
     * @param in
     * @param out
     */
    private static void delete(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("Delete Express");
        System.out.print("Please enter the express order number to delete:");
        String number = input.nextLine();
        int exist = Server.dao.findByNumber(number);
        if (exist == -1) {
            System.out.println("Express does not exist!");
        } else {
            int deleteNum;
            do {
                System.out.println("Delete?");
                System.out.println("1.confirm deletion");
                System.out.println("0.Cancel operation");
                String s = input.nextLine();
                deleteNum = -1;
                try {
                    deleteNum = validNum(s, 0, 1);
                    break;
                } catch (NumberFormatException | OutNumberBoundException e) {
                    System.out.println(e.getMessage());
                }
            } while (true);
            if (deleteNum == 0) {
                System.out.println("Cancel deletion succeeded!");
            } else {
                try {
                    out.writeUTF("delete");
                    out.writeUTF(number);
                    out.flush();
                    Object obj = in.readObject();
                    if (obj instanceof Boolean) {
                        boolean res = (boolean) obj;
                        if (res == true) {
                            System.out.println("Delete succeeded");
                        } else {
                            System.out.println("Deletion failed");
                        }
                    } else {
                        System.out.println("Deletion failed!!!!!!");
                    }
                } catch (Exception e) {
                    System.out.println("System exception, deletion failed!");
                    System.out.println(e.getMessage());
                }
            }// end else  option of delete
        }//end else express exist
    }//end method


    /**
     * Update Express
     * @param in
     * @param out
     */
    private static void update(ObjectInputStream in, ObjectOutputStream out) {
        System.out.println("---------Modify Express-----------");
        System.out.print("Please enter the courier number to be modified:");
        String number = input.nextLine();
        int exist = Server.dao.findByNumber(number);
        if(exist == -1){
            System.out.println("Express does not exist!");
        }else{
            Express newExpress = new Express();
            System.out.print("Please enter a new courier number:");
            newExpress.setNumber(input.nextLine());
            System.out.print("Please enter a new company name:");
            newExpress.setCompany(input.nextLine());
            try {
                out.writeUTF("update");
                out.flush();
                out.writeUTF(number);
                out.flush();
                out.writeObject(newExpress);
                out.flush();
                Object obj = in.readObject();
                if (obj instanceof Boolean) {
                    boolean res = (boolean) obj;
                    if (res == true) {
                        System.out.println("Update succeeded!");
                    } else {
                        System.out.println("Update failed!");
                    }
                } else{
                    System.out.println("Update failed!!!!!!");
                }
            } catch (Exception e) {
                System.out.println("System exception,Update failed!");
                System.out.println(e.getMessage());
            }
        }// end else(option of exist then update)
    }//end update method


    /**
     * User interface
     * @throws OutNumberBoundException
     * @throws Exception
     */
    public static void userPlatform(ObjectInputStream in, ObjectOutputStream out) throws OutNumberBoundException, Exception {
        int code = -1;
        do {
            System.out.print("Please enter the pickup Code:");
            String s = input.nextLine();
            try {
                code = validNum(s, 100000, 999999);
                break;
            } catch (NumberFormatException | OutNumberBoundException e) {
                System.out.println(e.getMessage());
            }
        } while (true);
        out.writeUTF("findByCode");
        out.writeInt(code);
        out.flush();
        Object obj = in.readObject();
        if (obj instanceof Express) {
            Express e = (Express) obj;
            System.out.println("Express information:" + e);
            System.out.println("Your express is stored in the second section of the express cabinet" + (e.getX() + 1) + "Row,The first" + (e.getY() + 1) + "column,Have a nice pick-up~");

        } else {
            System.out.println("Express doesn't exist, pick-up failed!");
        }
    }
    
}

Keywords: Java socket Multithreading

Added by taiger on Sat, 04 Sep 2021 08:00:49 +0300