高级编程--XML+socket练习题

<?xml version="1.0" encoding="GBK"?>

<citys>

<city id='010'>

<cityname>北京</cityname>

<cityarea>华北</cityarea>

<population>2114.8万人</population>

</city>

<city id='021'>

<cityname>上海</cityname>

<cityarea>华东</cityarea>

<population>2,500万人</population>

</city>

<city id='020'>

<cityname>广州</cityname>

<cityarea>华南</cityarea>

<population>1292.68万人</population>

</city>

<city id='028'>

<cityname>成都</cityname>

<cityarea>华西</cityarea>

<population>1417万人</population>

</city>

</citys>

(1)使用dom4j将信息存入xml中

(2)读取信息,并打印控制台

(3)添加一个city节点与子节点

(4)使用socket TCP协议编写服务端与客户端,

客户端输入城市ID,服务器响应相应城市信息

(5)使用socket TCP协议编写服务端与客户端,客户端要求用户输入city对象,服务端接收并使用dom4j保存至XML文件

(1)(2)(3)

Manager

package homework01;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.SAXWriter;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 14:03
 * @Version: 1.0
 */

public class Manager {
    public Document document;
    public Manager() throws DocumentException {}
    //创建文件 并写入信息
    public void createxml(String filepath) throws IOException {
        document = DocumentHelper.createDocument();
        Element rootElement = document.addElement("citys");

        addInfo(rootElement,"010","北京","华北","2114.8万人");
        addInfo(rootElement,"021","上海","华东","2500万人");
        addInfo(rootElement,"028","南京","华西","1417万人");

        //写入
        OutputFormat output = new OutputFormat();
        XMLWriter writer = new XMLWriter(new FileWriter(filepath),output);
        writer.write(document);
        writer.close();
    }
    //写入信息
    public void addInfo(Element root,String id,String cityname,String cityarea,String population){
        Element city = root.addElement("city");
        city.addAttribute("id",id);
        city.addElement("cityname").addText(cityname);
        city.addElement("cityarea").addText(cityarea);
        city.addElement("population").addText(population);
    }
    //读取信息并打印
    public void readXML(String filepath) throws DocumentException {
        //创建编译器
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        List<Element> citys = rootElement.elements();
        for (Element city : citys){
            System.out.println("--------------------------");
            System.out.println("城市id:" + city.attributeValue("id"));
            System.out.println("城市名称:" + city.elementText("cityname"));
            System.out.println("城市区域:" + city.elementText("cityarea"));
            System.out.println("城市人口:" + city.elementText("population"));
        }
    }

    //添加city节点与子节点
    //添加city节点
    public void addcity(String filepath,String id,String cityname,String cityarea,String population) throws DocumentException, IOException {
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        addInfo(rootElement,id,cityname,cityarea,population);

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(filepath), format);
        writer.write(document);
        writer.close();
    }

    public String findCityById(String filepath,String id) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        document = saxReader.read(filepath);

        Element rootElement = document.getRootElement();
        List<Element> citys = rootElement.elements();

        for (Element el : citys){
            if (el.attributeValue("id").equals(id)){
                return "城市id:" + el.attributeValue("id") + "\t城市名称:" + el.elementText("cityname") + "\t城市区域:" + el.elementText("cityarea")
                        + "\t城市人口:" + el.elementText("population");
            }
        }
        return "没有找到";
    }

}

Test

package homework01;

import homework01.Manager;
import org.dom4j.DocumentException;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 12:02
 * @Version: 1.0
 */

public class Test {
    public static void main(String[] args) {
        try {
            Manager manager = new Manager();
            manager.createxml("./src/homework01/1.xml");

            manager.addcity("./src/homework01/1.xml","100","河南","华中","9936.6万人");

            manager.readXML("./src/homework01/1.xml");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

(4)(5)

cityServer

package homework01;

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

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 17:17
 * @Version: 1.0
 */

public class cityServer {
    public static void main(String[] args) {

        try {
            Manager manager = new Manager();
            ServerSocket serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动,监听端口为8088");
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            do{
                InputStream is = socket.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                PrintWriter output = new PrintWriter(socket.getOutputStream(),true);
                String select = br.readLine();
//                System.out.println(select);


                if ("0".equals(select)){
                    break;
                }
                System.out.println(select);
                //根据id查信息
                if ("1".equals(select)){
                    String clientId = br.readLine();
                    System.out.println(clientId);
                    String cityInfo = manager.findCityById("./src/homework01/1.xml",clientId);
                    output.println(cityInfo);
                }


                //添加信息
                if ("2".equals(select)){
                    String clientId = br.readLine();
                    String cityname = br.readLine();
                    String cityarea = br.readLine();
                    String population = br.readLine();
                    manager.addcity("./src/homework01/1.xml",clientId,cityname,cityarea,population);
                    output.println("添加成功");
                }


            }while(true);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

cityClient

package homework01;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Author: Insight
 * @Description: TODO
 * @Date: 2024/9/12 17:17
 * @Version: 1.0
 */

public class cityClient {
    public static void main(String[] args) throws IOException {
        String host = "localhost";
        int port = 8088;
        Socket socket = new Socket(host, port);

        try {
            do{
                PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

                System.out.println("请输入您要选择的操作:1、查看城市信息   2、添加城市  0、退出");
                String select = reader.readLine();
                output.println(select);
                if ("0".equals(select)){
                    socket.close();
                    break;
                }
                if ("1".equals(select)){
                    System.out.println("请输入城市ID");
                    String clientId = reader.readLine();
                    output.println(clientId);
                }

                if ("2".equals(select)){
                    System.out.println("请输入城市ID");
                    String clientId = reader.readLine();
                    System.out.println("请输入城市信息:");
                    System.out.println("城市名称:");
                    String cityname = reader.readLine();
                    System.out.println("城市区域:");
                    String cityarea = reader.readLine();
                    System.out.println("城市人口:");
                    String population = reader.readLine();
                    output.println(clientId);
                    output.println(cityname);
                    output.println(cityarea);
                    output.println(population);

                }


                String serverResponse = input.readLine();
//                while (serverResponse != null){
                    System.out.println("Server response: " + serverResponse);
//                }

            }while(true);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
相关推荐
Themberfue几秒前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
plmm烟酒僧2 分钟前
Windows下QT调用MinGW编译的OpenCV
开发语言·windows·qt·opencv
测试界的酸菜鱼14 分钟前
Python 大数据展示屏实例
大数据·开发语言·python
让学习成为一种生活方式17 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画23 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin
Black_Friend31 分钟前
关于在VS中使用Qt不同版本报错的问题
开发语言·qt
南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
希言JY1 小时前
C字符串 | 字符串处理函数 | 使用 | 原理 | 实现
c语言·开发语言
残月只会敲键盘1 小时前
php代码审计--常见函数整理
开发语言·php
xianwu5431 小时前
反向代理模块
linux·开发语言·网络·git