android實現簡單的聊天室

     先說一下流程。首先是創建一個java工程,並建立兩個java類,一個用於接收到客戶端的鏈接,並把鏈接添加list中,第二類實現線程runnable接口,專門用來接收發送客戶發送的信息。其次,創建android工程,並建立兩個類,一個用於顯示聊天界面,另外一個負責接收服務器端返回的信息。這個例子確定會有考慮不周的地方可是隻是爲了學習android中網絡相關api的使用,因此請你們謹慎拍磚。 html

首先仍是android的內容 java


[html]  view plain copy print ?
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent" >  
  5.   
  6.     <EditText  
  7.         android:id="@+id/et_show"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:lines="5"  
  11.         android:hint="全部聊天信息"  
  12.         android:gravity="center"  
  13.          />  
  14.     <EditText  
  15.         android:id="@+id/et_input"  
  16.         android:layout_below="@+id/et_show"  
  17.         android:layout_width="fill_parent"  
  18.         android:layout_height="wrap_content"  
  19.         android:hint="輸入聊天信息"  
  20.         android:gravity="center"  
  21.          />  
  22.     <Button   
  23.         android:id="@+id/bt_send"  
  24.         android:layout_below="@+id/et_input"  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="發送信息"  
  28.         />  
  29. </RelativeLayout>  

接着是MainAvitvity.java



[java]  view plain copy print ?
  1. public class MainActivity extends Activity {  
  2.       
  3.     private EditText et_show,et_input;  
  4.     private Button bt_send;  
  5.     private OutputStream os;  
  6.     private Handler handler;  
  7.   
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.activity_main);  
  12.           
  13.         et_input = (EditText) this.findViewById(R.id.et_input);  
  14.         et_show = (EditText) this.findViewById(R.id.et_show);  
  15.         bt_send = (Button) this.findViewById(R.id.bt_send);  
  16.           
  17.           
  18.         try {  
  19.             //定義客戶鏈接的socket  
  20.             Socket socket = new Socket("本機IP",30000);  
  21.             //啓動客戶端監聽線程  
  22.             new Thread(new ClinetThread(socket,handler)).start();  
  23.             os = socket.getOutputStream();  
  24.         } catch (UnknownHostException e) {  
  25.             e.printStackTrace();  
  26.         } catch (IOException e) {  
  27.             e.printStackTrace();  
  28.         }  
  29.           
  30.           
  31.         bt_send.setOnClickListener(new OnClickListener() {  
  32.             @Override  
  33.             public void onClick(View v) {  
  34.                 try {  
  35.                     //獲得輸入框中的內容,寫入到輸入流中  
  36.                     os.write((et_input.getText().toString()+"\r\n").getBytes("utf-8"));  
  37.                     et_input.setText("");  
  38.                 } catch (UnsupportedEncodingException e) {  
  39.                     // TODO Auto-generated catch block  
  40.                     e.printStackTrace();  
  41.                 } catch (IOException e) {  
  42.                     // TODO Auto-generated catch block  
  43.                     e.printStackTrace();  
  44.                 }  
  45.             }  
  46.         });  
  47.           
  48.           
  49.         handler = new Handler(){  
  50.             @Override  
  51.             public void handleMessage(Message msg) {  
  52.                 super.handleMessage(msg);  
  53.                 if(msg.what == 1){  
  54.                     //獲得服務器返回的信息  
  55.                     et_show.append("\n"+msg.obj.toString());  
  56.                 }  
  57.             }  
  58.         };  
  59.     }  
  60.       
  61. }  

第三是客戶端的線程類



[java]  view plain copy print ?
  1. public class ClinetThread implements Runnable{  
  2.   
  3.     Socket socket = null;  
  4.     Handler handler = null;  
  5.       
  6.     BufferedReader br = null;  
  7.       
  8.     public ClinetThread(Socket socket,Handler handler) {  
  9.         this.socket = socket;  
  10.         this.handler = handler;  
  11.         try {  
  12.             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.           
  17.     }  
  18.       
  19.     @Override  
  20.     public void run() {  
  21.         String content = null;  
  22.         try {  
  23.             while((content = br.readLine())!=null){  
  24.                 Message msg = new Message();  
  25.                 msg.what = 1;  
  26.                 msg.obj = content;  
  27.                 handler.sendMessage(msg);  
  28.             }  
  29.         } catch (IOException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.       
  34. }  

接下來是Java工程中的主類



[java]  view plain copy print ?
  1. /** 
  2.  * 建立ServerSocket監聽的主類 
  3.  * 該類只負責接收客戶端的socket鏈接請求,每當客戶端 
  4.  * 鏈接到該serversocket以後,程序將對應socket加入到list 
  5.  * 併爲該socket開一挑單獨的線程,負責socket的全部通訊任務 
  6.  * @author Administrator 
  7.  * 
  8.  */  
  9. public class SimpleServer {  
  10.       
  11.     //定義保存全部Socket的ArrayList  
  12.     public static ArrayList<Socket> socketList = new ArrayList<Socket>();  
  13.       
  14.     public static void main(String[] args) {  
  15.         try {  
  16.             ServerSocket ss = new ServerSocket(30000);  
  17.             while (true) {  
  18.                 Socket s = ss.accept();  
  19.                 socketList.add(s);  
  20.                 new Thread(new ServerThead(s)).start();  
  21.             }  
  22.         } catch (IOException e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.           
  26.     }  
  27. }  

其次java工程中的線程類



[java]  view plain copy print ?
  1. /** 
  2.  * 負責每一個線程通訊的類 
  3.  * 該類不斷讀取客戶端數據,使用自定義的readFromClient()方法讀取 
  4.  * 客戶端數據,若是出現異常代表該socket對應的客戶端socket出現了問題 
  5.  * 程序將該socket從list中移除。 
  6.  * 當服務器線程讀取到了客戶端數據後,遍歷list集合,並將數據發送到每一個 
  7.  * socket中 
  8.  * @author Administrator 
  9.  * 
  10.  */  
  11. public class ServerThead implements Runnable {  
  12.   
  13.     //定義當前線程處理的socket  
  14.     Socket s = null;  
  15.     //該線程所處理的socket對應的輸入流  
  16.     BufferedReader br = null;  
  17.       
  18.     public ServerThead(Socket s) throws IOException {  
  19.         this.s = s;  
  20.         br = new BufferedReader(new InputStreamReader(s.getInputStream()));  
  21.     }  
  22.   
  23.     @Override  
  24.     public void run() {  
  25.         String conntent = null;  
  26.         while((conntent=readFromClient())!=null){  
  27.             //遍歷socket中的每個socket  
  28.             for(Socket s:SimpleServer.socketList){  
  29.                 try {  
  30.                     OutputStream os = s.getOutputStream();  
  31.                     os.write((conntent+"\n").getBytes("utf-8"));  
  32.                 } catch (IOException e) {  
  33.                     e.printStackTrace();  
  34.                 }  
  35.                   
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     private String readFromClient() {  
  41.         try {  
  42.             return br.readLine();  
  43.         } catch (IOException e) {  
  44.             e.printStackTrace();  
  45.             SimpleServer.socketList.remove(s);  
  46.         }  
  47.         return null;  
  48.     }  
  49.   
  50. }  
  51. 轉載請標明出處:雅荷灣
相關文章
相關標籤/搜索