### 综合练习 使用 Socket 和多线程编写一个简单的聊天小程序,要求客户端和服务端交替发送消息,在客户端和服务端都能看到彼此的聊天记录。 Server ```java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(8080); System.out.println("服务端已启动"); while(true) { socket = serverSocket.accept(); new Thread(new SocketThread(socket)).start();; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` ServerThread ```java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner; public class SocketThread implements Runnable { private Socket socket; public SocketThread(Socket socket) { this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; Scanner scanner = new Scanner(System.in); String message = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { while(true) { //读 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); message = dataInputStream.readUTF(); System.out.println("客户端:"+message); //写 System.out.print("服务器:"); message = scanner.next(); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(message); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` Client ```java import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client { public static void main(String[] args) { Socket socket = null; InputStream inputStream = null; DataInputStream dataInputStream = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; System.out.println("客户端已启动..."); try { socket = new Socket("127.0.0.1", 8080); Scanner scanner = new Scanner(System.in); String message = null; while(true) { //写 System.out.print("客户端:"); message = scanner.next(); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(message); //读 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); message = dataInputStream.readUTF(); System.out.println("服务器:"+message); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); dataOutputStream.close(); outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } ``` ### XML 解析 XML:Extensible Markup Language 可扩展标记语言 特点: XML 与操作系统无关、与编程语言无关,可以实现不同系统之间的数据交换。 XML 文档内容由一系列标签元素组成 <标签名 属性名="属性值">元素内容</标签名> - 属性值用双引号包裹 - 一个元素可以包含多个属性 - 属性值中不能直接包含<、>、"、&、' ```xml <?xml version="1.0" encoding="UTF-8"?> <books> <book id="001"> <author>张三</author> <name>Java高级编程</name> <description>Java是一门面向对象高级编程语言</description> </book> <book id="002" author="李四" name="C#" description="面向对象"></book> </books> ``` 注意事项 - 所有 XML 元素都必须有结束标签 - XML 标签对大小写敏感 - XML 必须有正确的嵌套 - 同级标签以缩进对齐 - 元素名称可以包含字母、数字或其他字符 - 元素名称不能以数字或标点符号开头 - 元素名称不能包含空格 XML 的转义字符 特殊字符:< > " ' & 转义符: ``` < > " ' & ``` 衣服型号 对应身高 S <165 M 165-170 L 170-175 XL 175-180 XXL 180-185 ```xml <?xml version="1.0" encoding="UTF-8"?> <cloth> <size range="height>165">S</size> <size range="165<height<170">M</size> <size range="170<height<175">L</size> <size range="175<height<180">XL</size> <size range="180<height<185">XXL</size> </cloth> ``` 考生姓名 预计得分 实际得分 张三 75 80 李四 75 88 ```xml <?xml version="1.0" encoding="UTF-8"?> <students> <student name="张三" expected_score="75" score="80"></student> <student name="李四" expected_score="75" score="88"></student> </students> ``` ### 解析XML 用 Java 程序读取、操作 XML 文件中的数据 dom4j 主流的 Java XML API,性能优异,功能强大。 ```xml <?xml version="1.0" encoding="GBK"?> <phoneinfo id="1"> <brand name="华为"> <type name="U8650"></type> <type name="HW123"></type> <type name="HW321"></type> </brand> <brand name="苹果"> <type name="iPhone"></type> </brand> <brand name="三星"> <type name="Note4"></type> </brand> </phoneinfo> ``` ```java import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test { public static void main(String[] args) { SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read("src/phone.xml"); //获取根节点 Element root = document.getRootElement(); Iterator<Element> rootIter = root.elementIterator(); while(rootIter.hasNext()) { Element ele = rootIter.next(); String name = ele.attributeValue("name"); System.out.println(name); Iterator<Element> eleIter = ele.elementIterator(); while(eleIter.hasNext()) { Element type = eleIter.next(); String typeName = type.attributeValue("name"); System.out.println(typeName); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` ```java import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Test2 { public static void main(String[] args) { SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read("src/phone.xml"); Element root = document.getRootElement(); Element newEle = root.addElement("brand"); newEle.addAttribute("name", "Vivo"); Element type = newEle.addElement("type"); type.addAttribute("name", "型号1"); OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); Writer fileWriter = new FileWriter("src/phone.xml"); XMLWriter writer = new XMLWriter(fileWriter,format); writer.write(document); writer.close(); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ```
Client.java
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client { public static void main(String[] args) { Socket socket = null; InputStream inputStream = null; DataInputStream dataInputStream = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; System.out.println("客户端已启动..."); try { socket = new Socket("127.0.0.1", 8080); Scanner scanner = new Scanner(System.in); String message = null; while(true) { //写 System.out.print("客户端:"); message = scanner.next(); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(message); //读 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); message = dataInputStream.readUTF(); System.out.println("服务器:"+message); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataInputStream.close(); inputStream.close(); dataOutputStream.close(); outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
cloth.xml
<?xml version="1.0" encoding="UTF-8"?> <cloth> <size range="height>165">S</size> <size range="165<height<170">M</size> <size range="170<height<175">L</size> <size range="175<height<180">XL</size> <size range="180<height<185">XXL</size> </cloth>
phone.xml
<?xml version="1.0" encoding="UTF-8"?> <phoneinfo id="1"> <brand name="华为"> <type name="U8650"/> <type name="HW123"/> <type name="HW321"/> </brand> <brand name="苹果"> <type name="iPhone"/> </brand> <brand name="三星"> <type name="Note4"/> </brand> <brand name="Vivo"/> <brand name="Vivo"> <type name="型号1"/> </brand> </phoneinfo>
score.xml
<?xml version="1.0" encoding="UTF-8"?> <students> <student name="张三" expected_score="75" score="80"></student> <student name="李四" expected_score="75" score="88"></student> </students>
Server.java
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(8080); System.out.println("服务端已启动"); while(true) { socket = serverSocket.accept(); new Thread(new SocketThread(socket)).start();; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
SocketThread.java
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.Scanner; public class SocketThread implements Runnable { private Socket socket; public SocketThread(Socket socket) { this.socket = socket; } @Override public void run() { // TODO Auto-generated method stub InputStream inputStream = null; DataInputStream dataInputStream = null; Scanner scanner = new Scanner(System.in); String message = null; OutputStream outputStream = null; DataOutputStream dataOutputStream = null; try { while(true) { //读 inputStream = socket.getInputStream(); dataInputStream = new DataInputStream(inputStream); message = dataInputStream.readUTF(); System.out.println("客户端:"+message); //写 System.out.print("服务器:"); message = scanner.next(); outputStream = socket.getOutputStream(); dataOutputStream = new DataOutputStream(outputStream); dataOutputStream.writeUTF(message); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { try { dataOutputStream.close(); outputStream.close(); dataInputStream.close(); inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Test.java
import java.util.Iterator; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Test { public static void main(String[] args) { SAXReader saxReader = new SAXReader(); try { Document document = saxReader.read("src/phone.xml"); //获取根节点 Element root = document.getRootElement(); Iterator<Element> rootIter = root.elementIterator(); while(rootIter.hasNext()) { Element ele = rootIter.next(); String name = ele.attributeValue("name"); System.out.println(name); Iterator<Element> eleIter = ele.elementIterator(); while(eleIter.hasNext()) { Element type = eleIter.next(); String typeName = type.attributeValue("name"); System.out.println(typeName); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
test.xml
<?xml version="1.0" encoding="UTF-8"?> <books> <book id="001"> <author>张三</author> <name>Java高级编程</name> <description>Java是一门面向对象高级编程语言</description> </book> <book id="002" author="李四" name="C#" description="面向对象"></book> </books>
Test2.java
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class Test2 {
public static void main(String[] args) {
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read("src/phone.xml");
Element root = document.getRootElement();
Element newEle = root.addElement("brand");
newEle.addAttribute("name", "Vivo");
Element type = newEle.addElement("type");
type.addAttribute("name", "型号1");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
Writer fileWriter = new FileWriter("src/phone.xml");
XMLWriter writer = new XMLWriter(fileWriter,format);
writer.write(document);
writer.close();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}