多線程實例---遠程聊天室(教你了了百行搭建聊天室)

前言:這是在以往學習過程當中,老師教授咱們的一個簡單的聊天室的示例,溫故而知新嘛,有不少本身當時沒有懂爲何要這樣寫的那些代碼,在如今倒是以爲當是如此。學習都同樣即要不斷地向前學習,也不要忘了,有好多東西須要鞏固
下面來講聊天室:java

ChatServer

package day17;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
 
public class ChatServer {
private ArrayList<TongXinThread> list =
        new ArrayList<>();
public void launch() {
    //啓動服務線程
    new Thread() {
        @Override
        public void run() {
           try {
              ServerSocket ss = new ServerSocket(8000);
              System.out.println("聊天室服務器已啓動");
              while(true) {
                 Socket s = ss.accept();
                 TongXinThread t =
                  new TongXinThread(s);
                 t.start();
              }
           } catch (Exception e) {
              System.out.println(
               "服務沒法在 8000 端口上啓動,或服務已經中止");
           }
        }
    }.start();
}
class TongXinThread extends Thread {
    Socket s;
    BufferedReader in;
    PrintWriter out;
    private String name;
    public TongXinThread(Socket s) {
        this.s = s;
    }
   
    public void send(String msg) {
        out.println(msg);
        out.flush();
    }
   
    public void sendAll(String msg) {
        synchronized (list) {
           for (TongXinThread t : list) {
              t.send(msg);
           }
        }
    }
   
    @Override
    public void run() {
        try {
           //UTF-8, 換行
           in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
           out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));            
           //接收客戶端的暱稱
           this.name = in.readLine();
           //把當前通訊線程實例,加入集合
           synchronized (list) {
              list.add(this);
           }
           //發送歡迎信息
           send("歡迎進入激情聊天室");
           //羣發上線消息
           sendAll(name+"進入了聊天室,在線人數:"+list.size());
          
           String line;
           while((line = in.readLine()) != null) {
              sendAll(name+"說:"+line);
           }
           //斷開
        } catch (Exception e) {
           //斷開
        }
        //刪除當前通訊線程實例
        synchronized (list) {
           list.remove(this);
        }
        //羣發離線消息
        sendAll(name+"離開了聊天室,在線人數:"+list.size());
       
       
    }
}
public static void main(String[] args) {
    ChatServer s = new ChatServer();
    s.launch();
}
}

ChatClient

package day17;
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Scanner;
 
public class ChatClient {
private Socket s;
private BufferedReader in;
private PrintWriter out;
private String name;
private LinkedList<String> list = new LinkedList<>();
private boolean flag; //開關
public void launch() {
    try {
        s = new Socket("192.168.21.61", 8000);
        in = new BufferedReader(new InputStreamReader(s.getInputStream(), "UTF-8"));
        out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"));              
        //暱稱
        System.out.print("起一個暱稱: ");
        name = new Scanner(System.in).nextLine();
        out.println(name);
        out.flush();
       
        //接收線程
        new Thread() {
           @Override
           public void run() {
              receive();
           }
        }.start();
       
        //輸入線程
        new Thread() {
           @Override
           public void run() {
              input();
           }
        }.start();
       
        //打印線程
        new Thread() {
           @Override
           public void run() {
              print();
           }
        }.start();
       
    } catch (Exception e) {
        System.out.println("沒法鏈接聊天室服務器");
        e.printStackTrace();
    }
}
protected void print() {
    while(true) {
        synchronized (list) {
           while (list.isEmpty() || flag) {
              try {
                 list.wait();
              } catch (InterruptedException e) {
              }
           }
           String msg = list.removeFirst();
           System.out.println(msg);
        }
    }
}
 
protected void input() {
    System.out.println("按回車輸入聊天內容");
   
    while(true) {
        new Scanner(System.in).nextLine();
        flag = true;//打開開關
       
        System.out.print("輸入聊天內容:");
        String s = new Scanner(System.in).nextLine();
        out.println(s);
        out.flush();
       
        flag = false;//關閉開關
        //通知打印線程能夠繼續打印
        synchronized (list) {
           list.notify();
        }
    }
}
 
protected void receive() {
    try {
        String line;
        while((line = in.readLine()) != null) {
           synchronized (list) {
              list.add(line);
              //通知打印線程已經有數據能夠打印了
              list.notify();
           }
        }
    } catch (Exception e) {
    }
    System.out.println("已經與服務器斷開鏈接");
}
 
public static void main(String[] args) {
    ChatClient c = new ChatClient();
    c.launch();
}
}
相關文章
相關標籤/搜索