android實現簡單的聊天室

來源:互聯網
上載者:User

練習android網路知識。先介紹一下大概流程。首先是建立一個java工程,並建立兩個java類,一個用於接收到用戶端的串連,並把串連添加list中,第二類實現線程runnable介面,專門用來接收發送客戶發送的資訊。其次,建立android工程,並建立兩個類,一個用於顯示聊天介面,另一個負責接收伺服器端返回的資訊。這個例子肯定會有考慮不周的地方但是只是為了學習android中網路相關api的使用,所以請大家謹慎拍磚。
首先還是android的內容
[html] 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
 
    <EditText 
        android:id="@+id/et_show" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:lines="5" 
        android:hint="所有聊天資訊" 
        android:gravity="center" 
         /> 
    <EditText 
        android:id="@+id/et_input" 
        android:layout_below="@+id/et_show" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:hint="輸入聊天資訊" 
        android:gravity="center" 
         /> 
    <Button  
        android:id="@+id/bt_send" 
        android:layout_below="@+id/et_input" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="發送資訊" 
        /> 
</RelativeLayout> 

接著是MainAvitvity.java
[java] 
public class MainActivity extends Activity { 
     
    private EditText et_show,et_input; 
    private Button bt_send; 
    private OutputStream os; 
    private Handler handler; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
         
        et_input = (EditText) this.findViewById(R.id.et_input); 
        et_show = (EditText) this.findViewById(R.id.et_show); 
        bt_send = (Button) this.findViewById(R.id.bt_send); 
         
         
        try { 
            //定義客戶串連的socket 
            Socket socket = new Socket("本機IP",30000); 
            //啟動用戶端監聽線程 
            new Thread(new ClinetThread(socket,handler)).start(); 
            os = socket.getOutputStream(); 
        } catch (UnknownHostException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
         
         
        bt_send.setOnClickListener(new OnClickListener() { 
            @Override 
            public void onClick(View v) { 
                try { 
                    //得到輸入框中的內容,寫入到輸入資料流中 
                    os.write((et_input.getText().toString()+"\r\n").getBytes("utf-8")); 
                    et_input.setText(""); 
                } catch (UnsupportedEncodingException e) { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } catch (IOException e) { 
                    // TODO Auto-generated catch block 
                    e.printStackTrace(); 
                } 
            } 
        }); 
         
         
        handler = new Handler(){ 
            @Override 
            public void handleMessage(Message msg) { 
                super.handleMessage(msg); 
                if(msg.what == 1){ 
                    //得到伺服器返回的資訊 
                    et_show.append("\n"+msg.obj.toString()); 
                } 
            } 
        }; 
    } 
     

第三是用戶端的線程類
[java] 
public class ClinetThread implements Runnable{ 
 
    Socket socket = null; 
    Handler handler = null; 
     
    BufferedReader br = null; 
     
    public ClinetThread(Socket socket,Handler handler) { 
        this.socket = socket; 
        this.handler = handler; 
        try { 
            br = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
         
    } 
     
    @Override 
    public void run() { 
        String content = null; 
        try { 
            while((content = br.readLine())!=null){ 
                Message msg = new Message(); 
                msg.what = 1; 
                msg.obj = content; 
                handler.sendMessage(msg); 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
    } 
     

接下來是Java工程中的主類
[java] 
/**
 * 建立ServerSocket監聽的主類
 * 該類只負責接收用戶端的socket串連請求,每當用戶端
 * 串連到該serversocket之後,程式將對應socket加入到list
 * 並為該socket開一挑單獨的線程,負責socket的所有通訊任務
 * @author Administrator
 *
 */ 
public class SimpleServer { 
     
    //定義儲存所有Socket的ArrayList 
    public static ArrayList<Socket> socketList = new ArrayList<Socket>(); 
     
    public static void main(String[] args) { 
        try { 
            ServerSocket ss = new ServerSocket(30000); 
            while (true) { 
                Socket s = ss.accept(); 
                socketList.add(s); 
                new Thread(new ServerThead(s)).start(); 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
         
    } 

其次java工程中的線程類
[java]
/**
 * 負責每個線程通訊的類
 * 該類不斷讀取用戶端資料,使用自訂的readFromClient()方法讀取
 * 用戶端資料,如果出現異常表明該socket對應的用戶端socket出現了問題
 * 程式將該socket從list中移除。
 * 當伺服器線程讀取到了用戶端資料後,遍曆list集合,並將資料發送到每個
 * socket中
 * @author Administrator
 *
 */ 
public class ServerThead implements Runnable { 
 
    //定義當前線程處理的socket 
    Socket s = null; 
    //該線程所處理的socket對應的輸入資料流 
    BufferedReader br = null; 
     
    public ServerThead(Socket s) throws IOException { 
        this.s = s; 
        br = new BufferedReader(new InputStreamReader(s.getInputStream())); 
    } 
 
    @Override 
    public void run() { 
        String conntent = null; 
        while((conntent=readFromClient())!=null){ 
            //遍曆socket中的每一個socket 
            for(Socket s:SimpleServer.socketList){ 
                try { 
                    OutputStream os = s.getOutputStream(); 
                    os.write((conntent+"\n").getBytes("utf-8")); 
                } catch (IOException e) { 
                    e.printStackTrace(); 
                } 
                 
            } 
        } 
    } 
 
    private String readFromClient() { 
        try { 
            return br.readLine(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
            SimpleServer.socketList.remove(s); 
        } 
        return null; 
    } 
 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.