项目用到的知识点:
IO流技术
网络编程技术
序列化
多线程
File等等
说明:
1). 客户端和服务器端采用 TCP 连接;2). 数据保存在服务器端以txt文件保存;3). 客户端增删改查发送数据格式说明:a). 添加: "[1] 数据 " ,例如: "[1] 李明明 , 男 ,22" ,意思:没有 id 字段,由服务器端在写入数据前自动添加。b). 根据 id 查询一条数据: "[2]id" ,例如: "[2]1" ,意思:查询 id 为 1 的学员信息c). 修改一条数据: "[3] 新数据 " 。例如:"[3]1,李明明, 女 ,19" ,意思:将 id=1 的学员改为后面的新数据。d). 查询所有数据: "[4]" 。例如: "[4]" ,意思:后面不用带任何数据。e). 删除一条数据: "[5]id" 。例如: "[5]1" ,意思:删除 id 为 1 的记录。
客户端:
package com.hh.client.pojo;
import java.io.Serializable;
public class Student implements Serializable {
private int id;
private String name;
private String sex;
private int age;
public Student() {
}
public Student( String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public Student(int id, String name, String sex, int age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
'}';
}
}
package com.hh.client.utils;
import com.hh.server.pojo.Student;
import java.util.ArrayList;
public class StudentUtils {
public static void printStudentList(ArrayList<Student> students){
System.out.println("-------------------------------------");
System.out.println("编号\t\t姓名\t\t性别\t\t年龄");
for (Student student : students) {
System.out.println(student.getId()+"\t\t"+student.getName()+"\t\t"+student.getSex()+"\t\t"+student.getAge());
}
System.out.println("-------------------------------------");
}
public static void printStudent(Student student){
System.out.println("-------------------------------------");
System.out.println("编号\t\t姓名\t\t性别\t\t年龄");
System.out.println(student.getId()+"\t\t"+student.getName()+"\t\t"+student.getSex()+"\t\t"+student.getAge());
}
}
package com.hh.client;
import com.hh.server.pojo.Student;
import com.hh.client.utils.StudentUtils;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Client {
public static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("---欢迎使用学生管理系统---");
while (true){
System.out.println("【1】添加学生【2】修改学生【3】删除学生【4】查询学生【5】查询所有学生 【6】退出");
System.out.println("请输入:");
int type = Integer.parseInt(scanner.nextLine());
switch (type){
case 1:
addStudent();
break;
case 2:
modifyStudent();
break;
case 3:
deleteStudent();
break;
case 4:
findByIdStudent();
break;
case 5:
findAllStudent();
break;
case 6:
System.exit(0);
break;
default:
System.out.println("输入错误,请重新输入!");
break;
}
}
}
//添加学生
private static void addStudent() {
System.out.println("---添加学生---");
System.out.println("请输入姓名:");
String name = scanner.nextLine();
System.out.println("请输入性别:");
String sex = scanner.nextLine();
System.out.println("请输入年龄:");
String age = scanner.nextLine();
if (name.isEmpty()||sex.isEmpty()||age.isEmpty()){
System.out.println("姓名,性别,年龄不能为空");
return;
}
//获取客户端
Socket socket = getSocket();
if (socket==null){
System.out.println("---服务器暂时无法连接---");
return;
}
try(OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();){
//向服务器传入数据
outputStream.write(("[1]"+name+","+sex+","+age).getBytes());
//从服务器获取数据
int result = inputStream.read();
if (result==1){
System.out.println("---添加成功---");
}else{
System.out.println("---添加失败,请重新添加---");
}
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
//修改学生
private static void modifyStudent() {
System.out.println("---修改学生---");
System.out.println("请输入学生id:");
String sid = scanner.nextLine();
if (sid.isEmpty()){
System.out.println("学生id不能为空");
return;
}
Socket socket = getSocket();
if (socket==null){
System.out.println("---服务器暂时无法连接---");
return;
}
Student student = null;
try(OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();) {
outputStream.write(("[4]"+sid).getBytes());
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
student = (Student)objectInputStream.readObject();
if (student==null){
System.out.println("查无此人");
return;
}else{
StudentUtils.printStudent(student);
}
socket.close();
}catch (IOException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
//以上内容为修改信息之前,先进行信息的查询,然后在进行修改
System.out.println("请输入新的姓名:(若不修改输入0):");
String name = scanner.nextLine();
System.out.println("请输入新的性别:(若不修改输入0):");
String sex = scanner.nextLine();
System.out.println("请输入新的年龄:(若不修改输入0):");
String age = scanner.nextLine();
if (!"0".equals(name)){
student.setName(name);
}
if (!"0".equals(sex)){
student.setSex(sex);
}
if (!"0".equals(age)){
student.setAge(Integer.parseInt(age));
}
Socket insertSocket = getSocket();
if (insertSocket==null){
System.out.println("---服务器暂时无法连接---");
return;
}
try (OutputStream outputStream = insertSocket.getOutputStream();
InputStream inputStream = insertSocket.getInputStream();){
outputStream.write(("[2]"+student.getName()+","+student.getSex()+","+student.getAge()).getBytes());
int read = inputStream.read();
if (read==1){
System.out.println("修改成功");
}else{
System.out.println("修改失败,请稍后重试");
}
//释放资源
insertSocket.close();
}catch (IOException e){
e.printStackTrace();
}
}
//删除学生
private static void deleteStudent() {
System.out.println("---删除学生---");
System.out.println("请输入你要删除学生的id:");
String sid = scanner.nextLine();
Socket deleteSocket = getSocket();
if (deleteSocket==null){
System.out.println("----服务器暂时无法连接----");
return;
}
Student student =null;
try (OutputStream outputStream = deleteSocket.getOutputStream();
InputStream inputStream = deleteSocket.getInputStream();){
outputStream.write(("[4]"+sid).getBytes());
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
student =(Student ) objectInputStream.readObject();
if (student==null){
System.out.println("---查无此人---");
return;
}else{
StudentUtils.printStudent(student);
}
deleteSocket.close();
}catch (IOException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
System.out.println("你确定要删除以上信息的学生吗(y/n)?");
String user = scanner.nextLine();
if (!"y".equals(user)){
System.out.println("---删除操作已经取消---");
return;
}
Socket socket = getSocket();
if (socket==null){
System.out.println("----服务器暂时无法连接----");
return;
}
try( OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();) {
outputStream.write(("[3]"+sid).getBytes());
int read = inputStream.read();
if (read==1){
System.out.println("删除成功");
}else{
System.out.println("删除失败,请稍后重试");
}
//释放资源
socket.close();
}catch (IOException e){}
}
//通过id查询学生
private static void findByIdStudent() {
System.out.println("---通过id查询学生---");
System.out.println("请输入你要查询学生的id:");
String sid = scanner.nextLine();
Socket findSocket = getSocket();
if (findSocket==null){
System.out.println("-----服务器暂时无法连接-----");
return;
}
Student student =null;
try (OutputStream outputStream = findSocket.getOutputStream();
InputStream inputStream = findSocket.getInputStream();){
outputStream.write(("[4]"+sid).getBytes());
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
student =(Student) objectInputStream.readObject();
if (student==null){
System.out.println("---查无此人---");
return;
}else{
StudentUtils.printStudent(student);
}
findSocket.close();
}catch (IOException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
//查询所有学生
private static void findAllStudent() {
System.out.println("---查询所有学生---");
Socket allSocket = getSocket();
if (allSocket==null){
System.out.println("--服务器暂时无法连接---");
return;
}
try(OutputStream outputStream = allSocket.getOutputStream();
InputStream inputStream = allSocket.getInputStream();) {
outputStream.write("[5]".getBytes());
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
ArrayList<Student> students = (ArrayList<Student>) objectInputStream.readObject();
System.out.println("student===="+students.size());
Student student = students.get(0);
System.out.println(student.getId());
System.out.println(student.getName());
System.out.println(student.getSex());
if (students==null||students.size()==0){
System.out.println("暂无学生信息");
}else{
StudentUtils.printStudentList(students);
}
allSocket.close();
}catch (IOException e){
e.printStackTrace();
}catch (ClassNotFoundException e){
e.printStackTrace();
}
}
//创建客户端
public static Socket getSocket(){
Socket socket = null;
try{
socket = new Socket("127.0.0.1",8888);
}catch (IOException e){
e.printStackTrace();
}
return socket;
}
}
服务器端:
package com.hh.server;
import com.hh.server.utils.ServerThread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
//一.业务功能: 1).接收客户端连接;
// 2).开启线程(ServerThread类)
public class Server {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = getServerSocket();
if (serverSocket==null){
System.out.println("服务器启动失败");
return;
}
while (true){
System.out.println("等待客户端连接...");
Socket accept = serverSocket.accept();
//开启新线程
new ServerThread(accept).start();
}
}
public static ServerSocket getServerSocket(){
ServerSocket serverSocket =null;
try {
serverSocket = new ServerSocket(8888);
}catch (IOException e){
e.printStackTrace();
}
return serverSocket;
}
}
package com.hh.server.utils;
import com.hh.server.pojo.Student;
import java.io.*;
import java.util.ArrayList;
public class ServerUtils {
public static void writeAll(ArrayList<Student> students){
try( FileWriter fileWriter = new FileWriter("students.txt",false);) {
for (Student student : students) {
fileWriter.write(student.getId()+","+student.getName()+","+student.getSex()+","+student.getAge());
fileWriter.write("\r\n");
}
}catch (Exception e){
e.printStackTrace();
}
}
//读取所有学生信息
public static ArrayList<Student> readAll(){
ArrayList<Student> students = new ArrayList<>();
File file = new File("students.txt");
if (!file.exists()){
try {
file.createNewFile();
}catch (Exception e){
e.printStackTrace();
}
}
try ( BufferedReader bufferedReader = new BufferedReader(new FileReader("students.txt"));){
String line = null;
while ((line=bufferedReader.readLine())!=null){
String[] infoStudent = line.split(",");
Student student = new Student();
student.setId(Integer.parseInt(infoStudent[0]));
student.setName(infoStudent[1]);
student.setSex(infoStudent[2]);
student.setAge(Integer.parseInt(infoStudent[3]));
students.add(student);
}
}catch (IOException e){
e.printStackTrace();
return null;
}
return students;
}
public static boolean addStudent(Student student){
ArrayList<Student> students = readAll();
if (students==null){
System.out.println("文件读取失败");
return false;
}
if (students.size()!=0){
student.setId(students.get(students.size()-1).getId()+1);
}else{
student.setId(1);
}
students.add(student);
writeAll(students);
return true;
}
public static boolean deleteById(String id){
ArrayList<Student> students = readAll();
if (students==null){
System.out.println("读取文件失败");
return false;
}
for (Student student : students) {
if (student.getId()== Integer.parseInt(id)){
students.remove(student);
writeAll(students);
return true;
}
}
return false;
}
public static boolean modify(Student student){
//1.先读取所有学生
ArrayList<Student> stuList = readAll();
if (stuList == null) {//说明读取文件出错
System.out.println("读取文件失败");
return false;
}
System.out.println("修改的数据:" + student);
//2.遍历集合
for (int i = 0; i < stuList.size(); i++) {
Student stu = stuList.get(i);
//3.判断哪个学生id和要修改的学生id相同
if (stu.getId() == student.getId()) {
//4.将学生改为新的学生
stuList.set(i, student);
//5.重写将集合写入到文集中
writeAll(stuList);//写回文件
//6.返回成功
return true;
}
}
//7.返回失败
return false;//没找到
}
//根据id查询学生,返回查询到的学生
public static Student findStudentById(String id) {
//1.先读取所有学生
ArrayList<Student> stuList = readAll();
if (stuList == null) {//说明读取文件出错
System.out.println("读取文件失败");
return null;
}
//2.遍历集合
for (int i = 0; i < stuList.size(); i++) {
Student stu = stuList.get(i);
//3.比较id
if (stu.getId() == Integer.parseInt(id)) {
//4.找到返回学生对象
return stu;
}
}
//5.找不到返回null
return null;
}
}
package com.hh.server.utils;
import com.hh.server.pojo.Student;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
public class ServerThread extends Thread{
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();){
byte[] bs = new byte[1024];
int len = inputStream.read(bs);
String bsStr = new String(bs, 0, len);
System.out.println("客户端的数据为:"+bsStr);
if (bsStr.charAt(0)!='['||bsStr.charAt(2) !=']'){
System.out.println("客户端数据格式有误");
outputStream.write("-1".getBytes());
outputStream.close();
inputStream.close();
socket.close();
return;
}
String num = bsStr.substring(1, 2);
String contentStr =bsStr.substring(3);
//判断
//【1】添加学生【2】修改学生【3】删除学生【4】查询学生【5】查询所有学生
switch (num){
case "1":
addStudent(contentStr);
break;
case "2":
modifyStudent(contentStr);
break;
case "3":
deleteStudent(contentStr);
break;
case "4":
findByIdStudent(contentStr);
break;
case "5":
findAllStudents();
break;
default:
System.out.println("客户端信息有误");
socket.close();
break;
}
}catch (IOException e){
e.printStackTrace();
}
}
//【1】添加学生【2】修改学生【3】删除学生【4】查询学生【5】查询所有学生
//查询学生 4 ,通过id
private void findByIdStudent(String contentStr) {
Student studentById = ServerUtils.findStudentById(contentStr);
try {
OutputStream out = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(studentById);
oos.close();
out.close();
socket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
//删除学生 3
private void deleteStudent(String contentStr) {
ServerUtils.deleteById(contentStr);
try {
OutputStream out = socket.getOutputStream();
out.write(1);
out.close();
socket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
//查询所有学生
private void findAllStudents() {
ArrayList<Student> students = ServerUtils.readAll();
try {
OutputStream out = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(students);
//释放资源
oos.close();
out.close();
socket.close();
} catch (IOException ie) {
ie.printStackTrace();
}
}
//修改学生
private void modifyStudent(String contentStr) {
String[] stuInfo = contentStr.split(",");
Student student = new Student(Integer.parseInt(stuInfo[0]),stuInfo[1], stuInfo[2],Integer.parseInt(stuInfo[3]));
ServerUtils.modify(student);
try( OutputStream outputStream = socket.getOutputStream();) {
outputStream.write(1);
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
//添加学生
private void addStudent(String contentStr) {
String[] stuInfo = contentStr.split(",");
Student student = new Student(stuInfo[0], stuInfo[1],Integer.parseInt(stuInfo[2]));
ServerUtils.addStudent(student);
try( OutputStream outputStream = socket.getOutputStream();) {
outputStream.write(1);
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
扫描二维码关注公众号,回复:
11110693 查看本文章