java實現(xiàn)Socket一對多問答型服務(wù)器
/**
* 實現(xiàn)一對多問答型服務(wù)器
* 一個服務(wù)器對多個客戶端,與每一個客戶端一對一通信
*/
public class QAndAServer1 {
? ?public static void main(String[] args) {
? ? ? ?try {
? ? ? ? ? ?ServerSocket ss = new ServerSocket(8888);
? ? ? ? ? ?System.out.println("服務(wù)器已啟動,等待連接中");
? ? ? ? ? ?while (true){
? ? ? ? ? ? ? ?new AutoAnswer(ss.accept()).start();
? ? ? ? ? ? ? ?//死循環(huán),不斷監(jiān)聽8888端口,每收到一個連接后創(chuàng)建一個自動回復(fù)線程來處理,服務(wù)器永不關(guān)閉
? ? ? ? ? ?}
? ? ? ?} catch (IOException e) {
? ? ? ? ? ?throw new RuntimeException(e);
? ? ? ?}
? ?}
}
class AutoAnswer extends Thread{
? ?final private Socket socket;
? ?public AutoAnswer(Socket socket) {
? ? ? ?this.socket = socket;
? ? ? ?//服務(wù)器將每一個客戶端的連接傳入一個新的線程對象中
? ?}
? ?public static String answerOf(String question){
? ? ? ?if (question.matches(".*([你好]|ni|hao|hello|hi|[在嗎]|親|[有人嗎]|[早中晚上]).*")){
? ? ? ? ? ?return "你好啊";
? ? ? ?}
? ? ? ?if (question.matches(".*[吃了嗎什么的].*")) {
? ? ? ? ? ?return "我沒吃,你呢";
? ? ? ?}
? ? ? ?if (question.matches(".*[問題?請?怎么辦].*")) {
? ? ? ? ? ?return "這邊會為您進行反饋,請耐心等待結(jié)果";
? ? ? ?}
? ? ? ?if (question.matches(".*[bye再見退出Exit關(guān)閉].*")){
? ? ? ? ? ?return "";
? ? ? ?}
? ? ? ?return "我不懂你的意思,請再說一遍";
? ?}
? ?@Override
? ?public void run() {
? ? ? ?try(PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
? ? ? ? ? ?BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
? ? ? ? ? ?System.out.println("收到客戶端"+socket.getInetAddress()+"的連接,通信已開始");
? ? ? ? ? ?pw.println("您好,人工智障"+this.getName().split("-")[1]+"號機為您服務(wù),您請說: ");
? ? ? ? ? ?//線程默認名字為Thread-數(shù)字,用-分割取1位為數(shù)字
? ? ? ? ? ?while (true){
? ? ? ? ? ? ? ?String answer = answerOf(br.readLine());
? ? ? ? ? ? ? ?if ("".equals(answer)){
? ? ? ? ? ? ? ? ? ?pw.println("再見~");
? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?pw.println(answer);
? ? ? ? ? ?}
? ? ? ? ? ?System.out.println("與客戶端"+socket.getInetAddress()+"的通信結(jié)束");
? ? ? ?} catch (IOException e) {
? ? ? ? ? ?throw new RuntimeException(e);
? ? ? ?}
? ? ? ?try {
? ? ? ? ? ?socket.close();
? ? ? ? ? ?//在線程內(nèi)將連接關(guān)閉
? ? ? ?} catch (IOException e) {
? ? ? ? ? ?throw new RuntimeException(e);
? ? ? ?}
? ?}
}