Java 利用网络编程实现机器人对话

news/2024/5/19 1:38:19 标签: java, 数据库, jdbc

Java学习

在学java的过程中去利用相应的知识做做小项目,可以加深对知识的掌握。

步骤:

  1. 创建相应的机器人语料数据库
  2. 创建服务端,在服务端将数据库连接起来,并根据客户端发送的消息去数据库获得相应的回复,然后发送给客户端
  3. 创建客户端,连接上服务端后与服务端进行通信

代码

数据库部分

dao:

java">package Study.socket.talktorobot;


public class RobotMsg {

  private long id;
  private String receive;
  private String response;


  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }


  public String getReceive() {
    return receive;
  }

  public void setReceive(String receive) {
    this.receive = receive;
  }


  public String getResponse() {
    return response;
  }

  public void setResponse(String response) {
    this.response = response;
  }

}

数据库连接部分:

java">package Study.socket.talktorobot;

import java.sql.*;

/**
 * @description:
 * @author : Qing Zhang
 * @time: 08
 */
public class DataBaseOfMsg {

    String driver_Name = "com.mysql.jdbc.Driver";
    String URL = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT";
    String USER_NAME = "root";
    String PASSWORD = "";
    Connection con = null;
    Statement s = null;


    public static void main(String[] args) {
        DataBaseOfMsg msg = new DataBaseOfMsg();
        msg.initial();

        System.out.println(msg.query("你好"));
    }


    /**
    * @Description: 初始化连接数据库
    * @Param: []
    * @return: void
    */
    public void initial() {
        this.initialDriver();
        this.connection();
        this.getStatement();
    }


    /**
     * @Description: 加载数据库
     * @Param: []
     * @return: void
     */
    private void initialDriver() {
        try {
            Class.forName(driver_Name);
            System.out.println("数据库驱动加载成功 !");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 获取连接
     * @Param: []
     * @return: void
     */
    private void connection() {
        try {
            con = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
            System.out.println("连接成功,获取连接对象: " + con);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 获取操作对象
     * @Param: []
     * @return: void
     */
    private void getStatement() {
        try {
            s = con.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * @Description: 创建msg表
     * @Param: []
     * @return: void
     */
    public void createTable() {
        String sql = "create table robot_msg(" +
                "id int," +
                "receive varchar(100)," +
                "response varchar(100)" +
                ")";
        try {
            s.execute(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    /**
    * @Description: 插入数据
    * @Param: [paraMsg]
    * @return: void
    */
    public void insertOfS(RobotMsg paraMsg) {
        String sql = "insert into robot_msg values(null," + "'" + paraMsg.getReceive() + "'" + "," + "'" + paraMsg.getResponse() + "'" + ")";
        try {
            s.execute(sql);
            System.out.println("执行插入语句成功");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }



    public void close() {
        if (s != null) {
            try {
                s.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    public void query() {
        String sql = "select * from robot_msg";
        try {
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt("id");// 可以使用字段名
                String receive = rs.getString(2);// 也可以使用字段的顺序
                String response = rs.getString(3);
                System.out.printf("%d\t%-16s\t%-16s\n", id, receive, response);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public String query(String paraReceive) {
        String sql = "select * from robot_msg where receive = '" + paraReceive+"'";
        try {
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                String response = rs.getString(3);
                return response;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "不知道怎么说";
    }
}

服务端

java">package Study.socket.talktorobot;

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

/**
 * @description: 服务端
 * @author : Qing Zhang
 * @time: 08
 */
public class SeverOfRobot {

    public static void main(String[] args) {

        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            System.out.println("服务端开启!!!");
            Socket s = serverSocket.accept();
            System.out.println("有客户端连接进来!!!");


            DataBaseOfMsg responseData = new DataBaseOfMsg();
            responseData.initial();

            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        InputStream is = s.getInputStream();
                        DataInputStream dis = new DataInputStream(is);
                        OutputStream os = s.getOutputStream();
                        DataOutputStream dos = new DataOutputStream(os);
                        while (true) {
                            String receive = dis.readUTF();
                            if (receive != null) {
                                String response = responseData.query(receive);
                                dos.writeUTF(response);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.start();
            thread.join();
            System.out.println("服务器关闭");
            s.close();
            serverSocket.close();
            responseData.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

客户端

java">package Study.socket.talktorobot;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @description:客户端
 * @author : Qing Zhang
 * @time: 08
 */
public class ClientOfRobot {

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

        //建立连接
        Socket socket = new Socket("localhost", 8888);
        System.out.println("开启客户端!!!");

        Thread thread = new Thread(){
            @Override
            public void run() {
                try {
                    //将输入流和输出流都加载
                    InputStream is = socket.getInputStream();
                    OutputStream os = socket.getOutputStream();
                    DataOutputStream dos = new DataOutputStream(os);
                    DataInputStream dis = new DataInputStream(is);
                    Scanner scanner = new Scanner(System.in);
                    while (true){
                        dos.writeUTF(scanner.nextLine());
                        System.out.println(dis.readUTF());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
        thread.start();
        try {
            thread.join();
            System.out.println("客户端退出!!!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

效果

在这里插入图片描述


http://www.niftyadmin.cn/n/1223936.html

相关文章

关键绩效指标法(KPI)初步概念

关键绩效指标法(KPI) 应用:企业管理领域:绩效考核理论基础:二八原理作用:用于衡量工作人员工作绩效表现的量化指标 关键绩效指标(KPI:Key Performance Indicator)是通过对组织内部流程的输入端…

随机森林算法及其实现(1)

随机森林算法及其实现 算法理解 随机森林就是通过集成学习的思想将多棵决策树集成的一种算法,它的基本单元是决策树,而它的本质属于机器学习的一大分支——集成学习(Ensemble Learning)方法。 这里随机的意思涉及到了另一个思想…

基于JAVA的广度优先遍历

算法分析课程作业(仅供参考) 源代码: import java.util.LinkedList; import java.util.Queue;/*** description: Breadth first search algorithm* author: Qing Zhang* time: 09*/ public class BFS {/*** Description: Breadth first sea…

基于JAVA的深度优先遍历

算法分析课程作业(仅供参考) 基于栈的实现方式 源代码: import java.util.Stack;/*** description: Depth first search algorithm* author: Qing Zhang* time: 09*/ public class DFS {/*** Description: Depth first search algorithm b…

基于JAVA的拓扑排序实现

算法分析课程作业(仅供参考) 源代码: import java.util.Arrays;/*** description: Topological Sort* author: Qing Zhang* time: 09*/ public class TopologicalSort {/*** Description: Judge whether the in-degree is 0* Param: [paraG…

配对算法(Gale-Shapley)实现

算法分析课程作业(仅供参考) 源代码: import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue;/*** description: Gale-Shapley algorithm* author: Qing Zhang* time: 09*/ public class …

随机森林算法及其实现(2)

随机森林算法及其实现 决策树部分参考了我导师的文章,日撸 Java 三百行(61-70天,决策树与集成学习) 1. 实现连续值的处理(参考西瓜书) 由于连续值的可取值数目不像离散值那样有明确的且数量较小的数值&a…