1. 程式人生 > >Socket程式設計實現簡易聊天室

Socket程式設計實現簡易聊天室

複製程式碼
 1   public class ServerThread implements Runnable {
 2   
 3       //定義當前執行緒所處理的Socket
 4       private Socket socket = null;
 5       //該執行緒所處理的Socket對應的輸入流
 6       private BufferedReader bufferedReader = null;
 7       
 8       /*
 9        * Function  :    ServerThread的構造方法
10        * Author    :    部落格園-依舊淡然
11    */ 12    public ServerThread(Socket socket) throws IOException { 13    this.socket = socket; 14    //獲取該socket對應的輸入流 15    bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); 16    } 17    18    /* 19    * Function : 實現run()方法,將讀到的客戶端內容進行廣播
20    * Author : 部落格園-依舊淡然 21    */ 22    public void run() { 23    try { 24    String content = null; 25    //採用迴圈不斷地從Socket中讀取客戶端傳送過來的資料 26    while((content = bufferedReader.readLine()) != null) { 27    //將讀到的內容向每個Socket傳送一次 28    for
(Socket socket : MyServer.socketList) { 29    //獲取該socket對應的輸出流 30    PrintStream printStream = new PrintStream(socket.getOutputStream()); 31    //向該輸出流中寫入要廣播的內容 32    printStream.println(packMessage(content)); 33    34    } 35    } 36    } catch(IOException e) { 37    e.printStackTrace(); 38    } 39    } 40    41    /* 42    * Function : 對要廣播的資料進行包裝 43    * Author : 部落格園-依舊淡然 44    */ 45    private String packMessage(String content) { 46    String result = null; 47    SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); //設定日期格式 48    if(content.startsWith("USER_ONE")) { 49    String message = content.substring(8); //獲取使用者傳送的真實的資訊 50    result = "\n" + "往事如風 " + df.format(new Date()) + "\n" + message; 51    } 52    if(content.startsWith("USER_TWO")) { 53    String message = content.substring(8); //獲取使用者傳送的真實的資訊 54    result = "\n" + "依舊淡然 " + df.format(new Date()) + "\n" + message; 55    } 56    return result; 57    } 58    59   }
複製程式碼