2018-05-09 聊天機器人練習(xí)

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

首先是在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同學(xué)');

這里要注意表的默認(rèn)編碼不支持中文凤巨,需要將表的編碼格式改成utf8

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

然后就可以編寫服務(wù)端和客戶端程序了督勺。
新建一個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;
    }
    //加載驅(qū)動
    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);
            //獲取查詢結(jié)果集
            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;
                //存儲獲取的結(jié)果到list中
                dictionaries.add(dictionary);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return dictionaries;
    }
}

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

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

服務(wù)端使用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.加載驅(qū)動
  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ù)庫查詢到回應(yīng)數(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í)行結(jié)果


執(zhí)行效果
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末贮尉,一起剝皮案震驚了整個濱河市拌滋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌猜谚,老刑警劉巖败砂,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異魏铅,居然都是意外死亡昌犹,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門览芳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來斜姥,“玉大人,你說我怎么就攤上這事沧竟≈簦” “怎么了?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵悟泵,是天一觀的道長杈笔。 經(jīng)常有香客問我,道長糕非,這世上最難降的妖魔是什么蒙具? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任球榆,我火速辦了婚禮,結(jié)果婚禮上禁筏,老公的妹妹穿的比我還像新娘持钉。我一直安慰自己,他們只是感情好融师,可當(dāng)我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布右钾。 她就那樣靜靜地躺著蚁吝,像睡著了一般旱爆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上窘茁,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天怀伦,我揣著相機與錄音,去河邊找鬼山林。 笑死房待,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的驼抹。 我是一名探鬼主播桑孩,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼框冀!你這毒婦竟也來了流椒?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤明也,失蹤者是張志新(化名)和其女友劉穎宣虾,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體温数,經(jīng)...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡绣硝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了撑刺。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片鹉胖。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖够傍,靈堂內(nèi)的尸體忽然破棺而出甫菠,到底是詐尸還是另有隱情,我是刑警寧澤王带,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布淑蔚,位于F島的核電站,受9級特大地震影響愕撰,放射性物質(zhì)發(fā)生泄漏刹衫。R本人自食惡果不足惜醋寝,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望带迟。 院中可真熱鬧音羞,春花似錦、人聲如沸仓犬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽搀继。三九已至窘面,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間叽躯,已是汗流浹背财边。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留点骑,地道東北人酣难。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像黑滴,于是被迫代替她去往敵國和親憨募。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,573評論 2 359