2018-05-09 聊天機器人練習

最近看了TCP和UDP協(xié)議之后,寫了個聊天機器人的練習。

首先是在mysql中新建一個名叫android的庫,以及名叫dictionary的表,使用的是命令行

#登錄mysql
mysql -u pabo -p
CREATE DATABASE android;
use android;
CREATE TABLE dictionary(
id INT,
receive varchar(100),
response varchar(100)
);

再往表里添加數(shù)據(jù)

INSERT INTO dictionary(id,receive,response) VALUES(1,'hi','你好'),
(2,'你叫什么','我是xx同學');

這里要注意表的默認編碼不支持中文,需要將表的編碼格式改成utf8

alter table dictionary modify receive varchar(100) set utf8;
alter table dictionary modify response varchar(100) set utf8;

然后就可以編寫服務端和客戶端程序了。
新建一個dictionary類,來保存數(shù)據(jù)庫中獲取到的數(shù)據(jù)。

public class Dictionary {
    int id;
    String receive;
    String response;
}

接著編寫DAO類,輔助數(shù)據(jù)庫連接

public class SQLDao {
    static String driver="com.mysql.jdbc.Driver";
    static String url="jdbc:mysql://localhost:3306/android?useUnicode=true&characterEncoding=utf8&useSSL=false";
    static String user="pabo";
    static String password="pabo";
    static Connection connection=null;
    public static Connection getConnection() throws SQLException{
        if(connection==null) {
            connection=DriverManager.getConnection(url,user,password);
        }
        return connection;
    }
    //加載驅動
    public static void Driver() throws ClassNotFoundException {
        Class.forName(driver);
    }
    public static List<Dictionary> query(String receive) throws SQLException {
        List<Dictionary> dictionaries=new ArrayList<Dictionary>();
        String sql= "select * from dictionary where receive = ?";
        Connection connection1 = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //建立連接
            connection1 = SQLDao.getConnection();
            preparedStatement=connection1.prepareStatement(sql);
            preparedStatement.setString(1, receive);
            //獲取查詢結果集
            resultSet=preparedStatement.executeQuery();         
            while(resultSet.next()) {
                Dictionary dictionary=new Dictionary();
                int id=resultSet.getInt("id");
                String receive1=resultSet.getString("receive");
                String response=resultSet.getString("response");
                dictionary.id=id;
                dictionary.receive=receive1;
                dictionary.response=response;
                //存儲獲取的結果到list中
                dictionaries.add(dictionary);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return dictionaries;
    }
}

在使用Statement語句執(zhí)行帶有中文的SQL語句時,時常遇到亂碼的問題,需要設置SQL語句編碼為UTF-8,在使用PreparedStatement沒有遇到編碼的問題

statement=connection.createStatement();
sql="select * from dictionary where receive= '你好'";
//將sql編碼設置為utf8,沒有中文亂碼的問題
sql=new String(sql.getBytes(),"UTF-8");
ResultSet resultSet=statement.executeQuery(sql);

服務端使用ServerSocket創(chuàng)建ServerSocket對象,端口號是1000

  ServerSocket serverSocket=new ServerSocket(10000);
  System.out.println("監(jiān)聽端口號:10000");
  Socket client=null;
  client=serverSocket.accept();
  InputStream inputStream=client.getInputStream();
  OutputStream outputStream=client.getOutputStream();
  //把輸入流封裝在DataInputStream
  DataInputStream dataInputStream=new DataInputStream(inputStream);
  DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
  //1.加載驅動
  SQLDao.Driver();
  String msg=null;  
  String sql="select * from dictionary where receive = ?";
  while(!"exit".equals(msg)) {
  //接收客戶端數(shù)據(jù) 
          msg=dataInputStream.readUTF();                        
      System.out.println("收到客戶端數(shù)據(jù):"+msg);
      //數(shù)據(jù)庫中查詢
      List<Dictionary> ds=new SQLDao().query(msg);
      String response=null;
      if(ds.isEmpty()) {
                System.out.println("未找到");
      }else {
                response=ds.get(0).response;
           }
      dataOutputStream.writeUTF(response);
      System.out.println("數(shù)據(jù)庫查詢到回應數(shù)據(jù):"+response);
        }
       dataInputStream.close();
       dataOutputStream.close();
       client.close();
       serverSocket.close();

客戶端

Socket client=new Socket("127.0.1.1", 10000);
InputStream inputStream=client.getInputStream();
OutputStream outputStream=client.getOutputStream();
DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
DataInputStream dataInputStream=new DataInputStream(inputStream);
Scanner scanner=new Scanner(System.in);
String string=null,string2 =null;
while(!"bye".equals(string)) {
    string=scanner.nextLine();
    dataOutputStream.writeUTF(string);
    string2=dataInputStream.readUTF();
    System.out.println(string2);
}
dataInputStream.close();
dataOutputStream.close();
outputStream.close();

執(zhí)行結果


執(zhí)行效果
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容