12.21-Android ServerSocket,12.21-android

來源:互聯網
上載者:User

12.21-Android ServerSocket,12.21-android

建立ServerSocket伺服器

1、new ServerSocket對象servierSocket

2、接收用戶端請求Socket client = servierSocket.accept();

3、以位元組流的方式迴圈讀取用戶端資料

4、對於要不要關閉用戶端和輸入輸出資料流的話,個人還是不太瞭解的。

     但是對於這個程式而言,可以實現的是,不斷接收用戶端的資料,並對該資料通過handler進行響應。

**************華麗的分割線**************

/**     * Socket伺服器     *      * @author Administrator     *     */    public class SocketServerDemo extends Thread {        @Override        public void run() {            // TODO Auto-generated method stub            super.run();            //Socket伺服器            ServerSocket serverSocket = null;            //Socket用戶端            Socket client = null;            //輸入資料流            InputStream ips = null;            //位元組            byte[] b = new byte[32];            try {
        //伺服器連接埠號碼 serverSocket = new ServerSocket(8777);
        //迴圈接收用戶端 while (true) { // 等待用戶端請求,如果沒有用戶端請求,會一直堵塞在這裡 client = serverSocket.accept(); ips = client.getInputStream(); try { //迴圈接收用戶端資訊 while(true){
                //按規定的位元組數讀取資料 int count = ips.read(b);
                //設定一樣位元組的位元組數組 byte temp[] = new byte[count];
                //以迴圈的方式接收資料 for (int i = 0; i < count; i++) { temp[i] = b[i]; } String str = new String(temp) ; if(str.equals("888")){ Message mes = new Message(); mes.what = 1; mhandler.sendMessage(mes); }else { Message mes = new Message(); mes.what = 2; mhandler.sendMessage(mes); } } } catch (Exception e) { e.printStackTrace(); } } } catch (IOException e1) { e1.printStackTrace(); } } }

 

聯繫我們

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