Android學習六:Socket 使用

來源:互聯網
上載者:User

標籤:

1socket的作用

通過http去擷取伺服器的資料在有些情況下是行不通的,所有使用socket與伺服器通訊也是必須掌握的

2.代碼

好了上代碼,代碼中有解釋,首先是簡單的服務端代碼

package org.tonny;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.ServerSocket;import java.net.Socket;public class SockServer implements Runnable{    private static final int PORT = 55555;    @Override    public void run()    {        //用於響應用戶端        Socket client = null;                //服務端socket        ServerSocket server = null;        try        {            //綁定連接埠,準備接受用戶端的串連            server = new ServerSocket(PORT);            while (true)            {                System.out.println("Wait for connecting...");                                //這個操作是阻塞的,有用戶端串連才會進行下一步操作                client = server.accept();                                //讀取用戶端發送的資料                BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));                String msg = in.readLine();                System.out.println("Client:  " + msg);            }        }        catch (Exception e)        {            System.out.println("Server Receive: Error");        }        finally        {            try            {                //關閉通訊端                server.close();                client.close();            }            catch (IOException e)            {                System.out.println("Server Receive: Error" + e.getMessage());            }        }    }    public static void main(String[] args)    {        Thread thread = new Thread(new SockServer());        thread.start();    }}

 

接著是android用戶端的代碼

package org.tonny.client;import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;import java.net.UnknownHostException;import android.app.Activity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;public class ClientActivity extends Activity{    // 需要發送的資訊寫在這個控制項中    private EditText txtInfo = null;    private static final int PORT = 55555;    @Override    protected void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_client);        txtInfo = (EditText) this.findViewById(R.id.txtInfo);    }    public void onBtnSendClick(View view)    {        String msg = txtInfo.getText().toString();                //不適用綫程通不過去,直接異常處理,這是因為android 3.0+以上 已經不建議在activity中添加耗時操作,要介面和資料脫離。4.0以上的通訊都必須放到線程裡去做 不能在UI線程。        //解決辦法,另起線程或Service處理socket。        SockClient sock = new SockClient("192.168.1.106", PORT, msg);        sock.start();    }    private final class SockClient extends Thread    {        private String ip;        private int port;        private String msg;        public SockClient(String ip, int port, String msg)        {            this.ip = ip;            this.port = port;            this.msg = msg;        }        @Override        public void run()        {            Socket client = null;            try            {                Log.d("CLIENT", "Connecting...");                // 與伺服器擷取串連                client = new Socket(ip, port);                // 擷取 Client 端的輸出資料流                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);                out.println(msg);            }            catch (UnknownHostException e)            {                Log.e("CLIENT", "Error", e);            }            catch (IOException e)            {                Log.e("CLIENT", "Error", e);            }            catch (Exception e)            {                Log.e("CLIENT", "Error", e);            }            finally            {                try                {                    if (client != null && !client.isClosed())                    {                        client.close();                    }                }                catch (IOException e)                {                    Log.e("TCP", "Error", e);                }            }        }    }}

 

要注意的是,socket操作一定要在單獨的線程中進行,否則會產生異常。

3.總結

還是一點,android操作socket的時候,應該線上程中執行,否則會報異常,為了這個花了不少時間調試,還是沒搞定,最後問的度娘。

Android學習六:Socket 使用

聯繫我們

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