1. 程式人生 > >基於Socket的Android與PC簡單聊天應用的實現

基於Socket的Android與PC簡單聊天應用的實現

實現Socket聊天其實質就是一個Socket的雙向通訊,分為服務端和客戶端,都是 需要得到一個socket物件,通過socket獲取流得到我們需要的資料。
標準的寫法都是開啟一個while(true)的執行緒不斷的去監聽接收訊息,另外啟一個執行緒去傳送訊息。為了方便演示效果這裡寫了一個Winform應用作為服務端。客戶端和服務端的程式碼基本上完全相同。下面給出
android收發資料主要程式碼。

接收資料:


    private class ReceiveThread extends Thread {
        private InputStream inStream = null
; private byte[] buffer; private String str = null; ReceiveThread(Socket socket) { try { inStream = socket.getInputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override
public void run() { while (true) { buffer = new byte[512]; try { inStream.read(buffer);//讀流方式應該和傳送一致 //(read、readUTF),否則阻塞 } catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); } try { str = new String(buffer, "UTF-8").trim(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (buffer.length > 0) { Message msg = Message.obtain(); msg.obj = str; msg.what = MSG_REC; myHandler.sendMessage(msg);//將獲取的資料傳送出去 } } } }

傳送資料:

    Runnable sendThread = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            byte[] sendBuffer = null;
            try {
                sendBuffer = strMessage.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                outStream = socket.getOutputStream();
                Message msg = Message.obtain();
                msg.obj = strMessage;
                msg.what = MSG_SEND;
                myHandler.sendMessage(msg);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                outStream.write(sendBuffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

來看看效果吧:
android:


android聊天截圖

PC:

PC端聊天截圖