Android---50---使用Socket進行通訊,androidsocket通訊

來源:互聯網
上載者:User

Android---50---使用Socket進行通訊,androidsocket通訊

使用Socket進行通訊:


通過Socket的構造方法串連指定的伺服器:


兩個構造方法:

Socket(InetAddress/String remoteAddress,int port):
建立串連到指定遠程主機、遠程連接埠的Socket,該構造器沒有指定本地地址,本地連接埠,預設使用本地主機的預設IP
地址,預設使用系統動態指定的IP地址


Socket(InetAddress/String remoteAddress,int port,InetAddress localAddr,int localPort):
建立串連到指定遠程主機、遠程連接埠的Socket,並指定本地IP地址和本地連接埠號碼,適用於本地主機有多個IP地址的情形。



 


擷取輸入資料流和輸出資料流:


getInputStream:
返回該Socket對象對應的輸入資料流

getOutputStream:
返回該Socket對象對應的輸出資料流



添加許可權:android.permission.INTERNET



protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_simple_client);show = (EditText) findViewById(R.id.show);new Thread() {@Overridepublic void run() {try {Socket socket = new Socket("192.168.3.12", 30005);BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));String line = br.readLine();show.setText("來自伺服器的資料:" + line);br.close();socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}.start();}





聯繫我們

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