Java TCP、IO流實現簡單機器人聊天系統

Java TCP、IO流實現簡單聊天機器人系統


一、效果:

        c.png


    (此係統基於java TCP信息傳遞,IO流實現人機聊天互動功能,詞庫可以自己加。)


二、主要知識點:

1、java.net
     類 Socket

    java.lang.Object    
      java.net.Socket

            此類實現客戶端套接字(也可以就叫“套接字”)。套接字是兩臺機器間通信的端點。

protectedSocket()通過系統默認類型的 SocketImpl 創建未連接套接字

protected

Socket(InetAddress address, int port)  創建一個流套接字並將其連接到指定 IP 地址的指定端口號。
 InputStreamgetInputStream()   返回此套接字的輸入流。

 OutputStreamgetOutputStream() 返回此套接字的輸出流。
 voidclose()關閉此套接字。

2、java.net
     類 ServerSocket

        此類實現服務器套接字。服務器套接字等待請求通過網絡傳入。它基於該請求執行某些操作,然後可能向請求者返回結果。

    java.lang.Object
      java.net.ServerSocket

 Socketaccept() 偵聽並接受到此套接字的連接。
 voidclose() 關閉此套接字。

3、java.io
     類 OutputStream

    java.lang.Object
      java.io.OutputStream

        此抽象類是表示輸出字節流的所有類的超類。輸出流接受輸出字節並將這些字節發送到某個接收器。

voidwrite(byte[] b) 將 b.length 個字節從指定的 byte 數組寫入此輸出流。
voidclose()關閉此輸出流並釋放與此流有關的所有系統資源。

4、java.io
     類 InputStream

    java.lang.Object

          java.io.InputStream

         此抽象類是表示字節輸入流的所有類的超類。

 intread(byte[] b)從輸入流中讀取一定數量的字節,並將其存儲在緩衝區數組 b 中。
voidclose() 關閉此輸入流並釋放與該流關聯的所有系統資源。

5、String 類的 getBytes()方法

 byte[]getBytes() 使用平臺的默認字符集將此 String 編碼爲 byte 序列,並將結果存儲到一個新的 byte 數組中。     

6、java.io
     類 BufferedInputStream

    java.lang.Object
      java.io.InputStream
      java.io.FilterInputStream
          java.io.BufferedInputStream

    BufferedInputStream 爲另一個輸入流添加一些功能,即緩衝輸入以及支持 markreset 方法的能力。在創建 BufferedInputStream 時,會創建一個內部緩衝區數組。在讀取或跳過流中的字節時,可根據需要從包含的輸入流再次填充該內部緩衝區,一次填充多個字節。mark 操作記錄輸入流中的某個點,reset 操作使得在從包含的輸入流中獲取新字節之前,再次讀取自最後一次 mark 操作後讀取的所有字節。

 

構造方法摘要
BufferedInputStream(InputStream in)創建一個 BufferedInputStream 並保存其參數,即輸入流 in,以便將來使用。

方法摘要
 intread(byte[] b)從此輸入流中將 byte.length 個字節的數據讀入一個 byte 數組中。
 voidclose() 關閉此輸入流並釋放與該流關聯的所有系統資源。

三、包和詞庫:

        圖片.png

    Chatbot.txt:詞庫文本(私信我發給你)

    MsgEx.txt  :聊天記錄文本


四、代碼:

   1、 客戶端:

package com.chatbot_TCP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/*
 * Chatbot 客戶端
 * 
 */
public class ChatbotClient {
    public static void main(String[] args) throws IOException {
        System.out.println("歐巴你來了!");
        boolean clientBL = true;
        while(clientBL){
            //創建Socket對象
            Socket server = new Socket(InetAddress.getLocalHost(),123);
            
            //獲取通道中的輸出流
            OutputStream clientOS = server.getOutputStream();
            String clientStr = new Scanner(System.in).nextLine();
            clientOS.write(clientStr.getBytes());
            //獲取通道中的輸入流
            InputStream clientIS = server.getInputStream();
            byte [] clientByte = new byte[1024];
            int clientLen = clientIS.read(clientByte);
            System.out.println("靜兒:"+new String(clientByte,0,clientLen));
            if("再見".equals(clientStr) || "over".equalsIgnoreCase(clientStr)){
                clientBL = false;
            }
            clientIS.close();
            clientOS.close();
        }
        //server.close();
    }
}

2、服務器端

package com.chatbot_TCP;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/*
 * Chatbot 服務器
 */
public class ChatbotServer {

    public static void main(String[] args) throws IOException {
        //創建ServerSocket對象
        ServerSocket ss = new ServerSocket(123);
        boolean bl = true;
        while(bl){
            
            //使用ss調用accept方法,獲取哪個客戶端
            Socket client = ss.accept();
            //獲取用戶的輸出流
            InputStream is = client.getInputStream();
            //使用輸出流對象的read方法,讀取數據
            byte[] bt = new byte[1024];
            int len = is.read(bt);
            String clientStr = new String(bt,0,len);
            
            //獲取通道中的輸出流
            OutputStream out = client.getOutputStream();
            
            //創建輸入流緩衝流
            BufferedReader br = new BufferedReader(new FileReader("Chatbot.txt"));
            //創建輸出流緩衝流
            BufferedWriter bw = new BufferedWriter(new FileWriter("MsgEx.txt",true));
            //DateFormat df = new SimpleDateFormat("HH:mm:ss");
            //讀取Chatbot.txt文本
            String chatbot = null;
            boolean enen = true;
            while((chatbot = br.readLine())!=null){
                
                String[] chatbotSplit = chatbot.split("-");
                if(clientStr.equalsIgnoreCase(chatbotSplit[0])){
                    byte [] chatbotByte = chatbotSplit[1].getBytes();
                    out.write(chatbotByte);
                    bw.write("我:"+clientStr);
                    bw.newLine();
                    bw.write("靜兒:"+chatbotSplit[1]);
                    bw.newLine();
                }else if("over".equalsIgnoreCase(clientStr) || "再見".equalsIgnoreCase(clientStr)){
                    out.write("歐巴再見".length());
                    bw.write("我:"+clientStr);
                    bw.write("靜兒:歐巴再見");
                    bw.newLine();
                    bl = false;
                }else if("聊天記錄".equals(clientStr) || "查看聊天".equals(clientStr)){
                    BufferedInputStream bisMsgEx = new BufferedInputStream(new FileInputStream("MsgEx.txt"));
                    OutputStream clientOut = client.getOutputStream();
                    int lenMsgEx = 0;
                    byte [] byteMsgEx = new byte[1024];
                    while((lenMsgEx = bisMsgEx.read(byteMsgEx))!=-1){
                        clientOut.write(byteMsgEx,0,lenMsgEx);
                    }
                }else{
                    enen = false;
                }
                
            }
            if(!enen){
                out.write("愛你喲".getBytes());
                bw.write("靜兒:愛你喲");
                bw.newLine();
            }
            //釋放資源
            bw.close();
            br.close();
            out.close();
            is.close();
            client.close();
        }
        //ss.close();//服務器一直循環,不停止
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章