網頁版線上聊天java Socket實現_java

來源:互聯網
上載者:User

本文為大家分享了一個滿足線上網頁交流需求的執行個體,由於java Socket實現的網頁版線上聊天功能,供大家參考,具體內容如下

實現步驟:
1、使用awt組件和socket實現簡單的單用戶端向服務端持續發送訊息;
2、結合線程,實現多用戶端串連服務端發送訊息;
3、實現服務端轉寄用戶端訊息至所有用戶端,同時在用戶端顯示;
4、把awt組件產生的視窗介面改成前端jsp或者html展示的介面,java socket實現的用戶端改為前端技術實現。

這裡首先實現第一步的簡易功能,痛點在於:
1、沒有用過awt組件,沒有用過java相關的監聽事件;
2、長時間沒有使用socket進行用戶端和服務端的互動,並且沒有真正進行過cs結構的開發。

實現功能的代碼
線上聊天用戶端:
1、產生圖形視窗介面輪廓
2、為輪廓添加關閉事件
3、在輪廓中加入輸入地區和內容展示框域
4、為輸入地區添加斷行符號事件
5、建立服務端串連並發送資料

package chat.chat;  import java.awt.BorderLayout; import java.awt.Frame; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException;  /**  * 線上聊天用戶端 1、產生圖形視窗介面輪廓 2、為輪廓添加關閉事件 3、在輪廓中加入輸入地區和內容展示框域 4、為輸入地區添加斷行符號事件  * 5、建立服務端串連並發送資料  *  * @author tuzongxun123  *  */ public class ChatClient extends Frame {   // 使用者輸入地區   private TextField tfTxt = new TextField();   // 內容展示框域   private TextArea tarea = new TextArea();   private Socket socket = null;   // 資料輸出資料流   private DataOutputStream dataOutputStream = null;    public static void main(String[] args) {     new ChatClient().launcFrame();   }    /**    * 建立一個簡單的圖形化視窗    *    * @author:tuzongxun    * @Title: launcFrame    * @param    * @return void    * @date May 18, 2016 9:57:00 AM    * @throws    */   public void launcFrame() {     setLocation(300, 200);     this.setSize(200, 400);     add(tfTxt, BorderLayout.SOUTH);     add(tarea, BorderLayout.NORTH);     pack();     // 監聽圖形介面視窗的關閉事件     this.addWindowListener(new WindowAdapter() {        @Override       public void windowClosing(WindowEvent e) {         System.exit(0);         disConnect();       }     });     tfTxt.addActionListener(new TFLister());     setVisible(true);     connect();   }    /**    * 串連伺服器    *    * @author:tuzongxun    * @Title: connect    * @param    * @return void    * @date May 18, 2016 9:56:49 AM    * @throws    */   public void connect() {     try {       // 建立服務端串連       socket = new Socket("127.0.0.1", 8888);       // 擷取用戶端輸出資料流       dataOutputStream = new DataOutputStream(socket.getOutputStream());       System.out.println("連上服務端");     } catch (UnknownHostException e) {       e.printStackTrace();     } catch (IOException e) {       e.printStackTrace();     }   }    /**    * 關閉用戶端資源    *    * @author:tuzongxun    * @Title: disConnect    * @param    * @return void    * @date May 18, 2016 9:57:46 AM    * @throws    */   public void disConnect() {     try {       dataOutputStream.close();       socket.close();     } catch (IOException e) {       e.printStackTrace();     }   }    /**    * 向服務端發送訊息    *    * @author:tuzongxun    * @Title: sendMessage    * @param @param text    * @return void    * @date May 18, 2016 9:57:56 AM    * @throws    */   private void sendMessage(String text) {     try {       dataOutputStream.writeUTF(text);       dataOutputStream.flush();     } catch (IOException e1) {       e1.printStackTrace();     }   }    /**    * 圖形視窗輸入地區監聽斷行符號事件    *    * @author tuzongxun123    *    */   private class TFLister implements ActionListener {      @Override     public void actionPerformed(ActionEvent e) {       String text = tfTxt.getText().trim();       tarea.setText(text);       tfTxt.setText("");       // 斷行符號後發送資料到伺服器       sendMessage(text);     }   } } 

服務端:

package chat.chat;  import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket;  /**  * java使用socket和awt組件簡單實現線上聊天功能服務端 可以實現一個用戶端串連後不斷向服務端發送訊息  * 但不支援多個用戶端同時串連,原因在於代碼中獲得用戶端串連後會一直迴圈監聽用戶端輸入,造成阻塞  * 以至於服務端無法二次監聽另外的用戶端,如要實現,需要使用非同步或者多線程  *  * @author tuzongxun123  *  */ public class ChatServer {    public static void main(String[] args) {     // 是否成功啟動服務端     boolean isStart = false;     // 服務端socket     ServerSocket ss = null;     // 用戶端socket     Socket socket = null;     // 服務端讀取用戶端資料輸入流     DataInputStream dataInputStream = null;     try {       // 啟動伺服器       ss = new ServerSocket(8888);     } catch (BindException e) {       System.out.println("連接埠已在使用中");       // 關閉程式       System.exit(0);     } catch (Exception e) {       e.printStackTrace();     }      try {       isStart = true;       while (isStart) {         boolean isConnect = false;         // 啟動監聽         socket = ss.accept();         System.out.println("one client connect");         isConnect = true;         while (isConnect) {           // 擷取用戶端輸入資料流           dataInputStream = new DataInputStream(               socket.getInputStream());           // 讀取用戶端傳遞的資料           String message = dataInputStream.readUTF();           System.out.println("用戶端說:" + message);         }        }     } catch (EOFException e) {       System.out.println("client closed!");     } catch (Exception e) {       e.printStackTrace();     } finally {       // 關閉相關資源       try {         dataInputStream.close();         socket.close();       } catch (IOException e) {         e.printStackTrace();       }     }   } } 

繼續,在單用戶端串連的基礎上,這裡第二步需要實現多用戶端的串連,也就需要使用到線程。每當有一個新的用戶端串連上來,服務端便需要新啟動一個線程進行處理,從而解決之前的迴圈讀取中造成阻塞的問題。

寫線程通常有兩種方法,整合Thread或者實現runnable介面,原則上是能實現runnable的情況下就不繼承,因為實現介面的方式更加靈活。

用戶端代碼相較之前沒有變化,變得是服務端,因此這裡便只貼出服務端代碼:

java使用socket和awt組件以及多線程簡單實現線上聊天功能服務端 :

實現多個用戶端串連後不斷向服務端發送訊息, 相對於第一個版本,重點在於使用了多線程。服務端還未實現轉寄功能,用戶端圖形視窗中只能看到自己輸入的資訊,不能看到其他用戶端發送的訊息。

package chat.chat;  import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException;  /**  * *  * @author tuzongxun123  *  */ public class ChatServer {    public static void main(String[] args) {     new ChatServer().start();   }    // 是否成功啟動服務端   private boolean isStart = false;   // 服務端socket   private ServerSocket ss = null;   // 用戶端socket   private Socket socket = null;    public void start() {     try {       // 啟動伺服器       ss = new ServerSocket(8888);     } catch (BindException e) {       System.out.println("連接埠已在使用中");       // 關閉程式       System.exit(0);     } catch (Exception e) {       e.printStackTrace();     }      try {       isStart = true;       while (isStart) {         // 啟動監聽         socket = ss.accept();         System.out.println("one client connect");         // 啟動用戶端線程         Client client = new Client(socket);         new Thread(client).start();       }     } catch (Exception e) {       e.printStackTrace();     } finally {       // 關閉服務       try {         ss.close();       } catch (IOException e) {         e.printStackTrace();       }     }    }    /**    * 用戶端線程    *    * @author tuzongxun123    *    */   class Client implements Runnable {     // 用戶端socket     private Socket socket = null;     // 用戶端輸入資料流     private DataInputStream dataInputStream = null;     private boolean isConnect = false;      public Client(Socket socket) {       this.socket = socket;       try {         isConnect = true;         // 擷取用戶端輸入資料流         dataInputStream = new DataInputStream(socket.getInputStream());       } catch (IOException e) {         e.printStackTrace();       }     }      @Override     public void run() {       isConnect = true;       try {         while (isConnect) {           // 讀取用戶端傳遞的資料           String message = dataInputStream.readUTF();           System.out.println("用戶端說:" + message);         }       } catch (EOFException e) {         System.out.println("client closed!");       } catch (SocketException e) {         System.out.println("Client is Closed!!!!");       } catch (Exception e) {         e.printStackTrace();       } finally {         // 關閉相關資源         try {           dataInputStream.close();           socket.close();         } catch (IOException e) {           e.printStackTrace();         }       }     }    }  } 

上面主要介紹了利用線程使服務端實現了能夠接收多用戶端請求的功能,這裡便需要用戶端接收多用戶端訊息的同時還能把訊息轉寄到每個串連的用戶端,並且用戶端要能在內容顯示地區顯示出來,從而實現簡單的線上群聊。

在實現用戶端轉寄,無非就是增加輸出資料流;而之前用戶端都只發不收,這裡也需要更改用戶端達到迴圈接收服務端訊息的目的,因此也需要實現多線程。

在實現這個功能的時候,偶然想起隨機產生驗證碼的功能,於是也靈機一動隨機給每個用戶端產生一個名字,從而在輸出的時候看起來更加像是群聊,不僅有訊息輸出,還能看到是誰。

實現這些功能之後,基本上就可以幾個人同時線上群聊了,因為代碼中有main方法,因此可以把服務端和用戶端都打成可執行jar包,可參考我的另一篇博文:使用eclipse建立java程式可執行jar包

之後在案頭雙擊相應的jar檔案啟動服務端和用戶端即可,不需要再依賴eclipse運行。

修改後的用戶端代碼如下:

package chat.chat;  import java.awt.BorderLayout; import java.awt.Frame; import java.awt.TextArea; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; import java.util.Random;  /**  * 線上聊天用戶端 步驟:  *1、產生圖形視窗介面輪廓  *2、為輪廓添加關閉事件  *3、在輪廓中加入輸入地區和內容展示框域  *4、為輸入地區添加斷行符號事件  * 5、建立服務端串連並發送資料  *  * @author tuzongxun123  *  */ public class ChatClient extends Frame {   /**    *    */   private static final long serialVersionUID = 1L;   // 使用者輸入地區   private TextField tfTxt = new TextField();   // 內容展示框域   private TextArea tarea = new TextArea();   private Socket socket = null;   // 資料輸出資料流   private DataOutputStream dataOutputStream = null;   // 資料輸入流   private DataInputStream dataInputStream = null;   private boolean isConnect = false;   Thread tReceive = new Thread(new ReceiveThread());   String name = "";    public static void main(String[] args) {     ChatClient chatClient = new ChatClient();     chatClient.createName();     chatClient.launcFrame();    }    /**    * 建立一個簡單的圖形化視窗    *    * @author:tuzongxun    * @Title: launcFrame    * @param    * @return void    * @date May 18, 2016 9:57:00 AM    * @throws    */   public void launcFrame() {     setLocation(300, 200);     this.setSize(200, 400);     add(tfTxt, BorderLayout.SOUTH);     add(tarea, BorderLayout.NORTH);     // 根據視窗裡面的布局及組件的preferedSize來確定frame的最佳大小     pack();     // 監聽圖形介面視窗的關閉事件     this.addWindowListener(new WindowAdapter() {        @Override       public void windowClosing(WindowEvent e) {         System.exit(0);         disConnect();       }     });     tfTxt.addActionListener(new TFLister());     // 設定視窗可見     setVisible(true);     connect();     // 啟動接受訊息的線程     tReceive.start();   }    /**    * 串連伺服器    *    * @author:tuzongxun    * @Title: connect    * @param    * @return void    * @date May 18, 2016 9:56:49 AM    * @throws    */   public void connect() {     try {       // 建立服務端串連       socket = new Socket("127.0.0.1", 8888);       // 擷取用戶端輸出資料流       dataOutputStream = new DataOutputStream(socket.getOutputStream());       dataInputStream = new DataInputStream(socket.getInputStream());       System.out.println("連上服務端");       isConnect = true;     } catch (UnknownHostException e) {       e.printStackTrace();     } catch (IOException e) {       e.printStackTrace();     }   }    // 產生隨機的用戶端名字   public void createName() {     String[] str1 = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",         "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",         "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8",         "9", "0", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",         "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",         "W", "X", "Y", "Z" };     Random ran = new Random();      for (int i = 0; i < 6; i++) {       // long num = Math.round(Math.random() * (str1.length - 0) + 0);       // int n = (int) num;       int n = ran.nextInt(str1.length);       if (n < str1.length) {         String str = str1[n];         name = name + str;         System.out.println(name);       } else {         i--;         continue;       }      }     this.setTitle(name);   }    /**    * 關閉用戶端資源    *    * @author:tuzongxun    * @Title: disConnect    * @param    * @return void    * @date May 18, 2016 9:57:46 AM    * @throws    */   public void disConnect() {     try {       isConnect = false;       // 停止線程       tReceive.join();     } catch (InterruptedException e) {       e.printStackTrace();     } finally {       try {         if (dataOutputStream != null) {           dataOutputStream.close();         }         if (socket != null) {           socket.close();           socket = null;         }        } catch (IOException e) {         e.printStackTrace();       }     }   }    /**    * 向服務端發送訊息    *    * @author:tuzongxun    * @Title: sendMessage    * @param @param text    * @return void    * @date May 18, 2016 9:57:56 AM    * @throws    */   private void sendMessage(String text) {     try {       dataOutputStream.writeUTF(name + ":" + text);       dataOutputStream.flush();     } catch (IOException e1) {       e1.printStackTrace();     }   }    /**    * 圖形視窗輸入地區監聽斷行符號事件    *    * @author tuzongxun123    *    */   private class TFLister implements ActionListener {      @Override     public void actionPerformed(ActionEvent e) {       String text = tfTxt.getText().trim();       // 清空輸入地區資訊       tfTxt.setText("");       // 斷行符號後發送資料到伺服器       sendMessage(text);     }    }    private class ReceiveThread implements Runnable {      @Override     public void run() {       try {         while (isConnect) {           String message = dataInputStream.readUTF();           System.out.println(message);           String txt = tarea.getText();           if (txt != null && !"".equals(txt.trim())) {             message = tarea.getText() + "\n" + message;           }           tarea.setText(message);         }       } catch (IOException e) {         e.printStackTrace();       }     }    } } 

修改後的服務端代碼如下:

package chat.chat;  import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.BindException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List;  /**  * java使用socket和awt組件以及多線程簡單實現線上聊天功能服務端 :  * 實現服務端把接收到的用戶端資訊轉寄到所有串連的用戶端,並且讓用戶端讀取到這些資訊並顯示在內容顯示地區中。  *  * @author tuzongxun123  *  */ public class ChatServer {    public static void main(String[] args) {     new ChatServer().start();   }    // 是否成功啟動服務端   private boolean isStart = false;   // 服務端socket   private ServerSocket ss = null;   // 用戶端socket   private Socket socket = null;   // 儲存用戶端集合   List<Client> clients = new ArrayList<Client>();    public void start() {     try {       // 啟動伺服器       ss = new ServerSocket(8888);     } catch (BindException e) {       System.out.println("連接埠已在使用中");       // 關閉程式       System.exit(0);     } catch (Exception e) {       e.printStackTrace();     }      try {       isStart = true;       while (isStart) {         // 啟動監聽         socket = ss.accept();         System.out.println("one client connect");         // 啟動用戶端線程         Client client = new Client(socket);          new Thread(client).start();         clients.add(client);       }     } catch (Exception e) {       e.printStackTrace();     } finally {       // 關閉服務       try {         ss.close();       } catch (IOException e) {         e.printStackTrace();       }     }    }    /**    * 用戶端線程    *    * @author tuzongxun123    *    */   private class Client implements Runnable {     // 用戶端socket     private Socket socket = null;     // 用戶端輸入資料流     private DataInputStream dataInputStream = null;     // 用戶端輸出資料流     private DataOutputStream dataOutputStream = null;     private boolean isConnect = false;      public Client(Socket socket) {       this.socket = socket;       try {         isConnect = true;         // 擷取用戶端輸入資料流         dataInputStream = new DataInputStream(socket.getInputStream());         // 擷取用戶端輸出資料流         dataOutputStream = new DataOutputStream(             socket.getOutputStream());       } catch (IOException e) {         e.printStackTrace();       }     }      /**      * 向用戶端群發(轉寄)資料      *      * @author:tuzongxun      * @Title: sendMessageToClients      * @param @param message      * @return void      * @date May 18, 2016 11:28:10 AM      * @throws      */     public void sendMessageToClients(String message) {       try {         dataOutputStream.writeUTF(message);       } catch (SocketException e) {        } catch (IOException e) {         e.printStackTrace();       }     }      @Override     public void run() {       isConnect = true;       Client c = null;       try {         while (isConnect) {           // 讀取用戶端傳遞的資料           String message = dataInputStream.readUTF();           System.out.println("用戶端說:" + message);           for (int i = 0; i < clients.size(); i++) {             c = clients.get(i);              c.sendMessageToClients(message);           }          }       } catch (EOFException e) {         System.out.println("client closed!");       } catch (SocketException e) {         if (c != null) {           clients.remove(c);         }         System.out.println("Client is Closed!!!!");       } catch (Exception e) {         e.printStackTrace();       } finally {         // 關閉相關資源         try {           if (dataInputStream != null) {             dataInputStream.close();           }           if (socket != null) {             socket.close();             socket = null;           }         } catch (IOException e) {           e.printStackTrace();         }       }     }   }  } 

就先為大家介紹到這裡,之後如果有新的內容再為大家進行更新。

關於網頁線上聊天功能的實現大,大家還可以參考一下幾篇文章進行學習:

java實現一個簡單TCPSocket聊天室功能分享

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家可以繼續關注云棲社區的更多精彩內容。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.