java伺服器端與android用戶端的通訊

來源:互聯網
上載者:User

標籤:

伺服器端的工作非常簡單,建立socket.監聽,代碼如下:

package com.hdc.socket;import java.io.IOException;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class JavaServer {public static void main(String[] args) {try {ServerSocket server = new ServerSocket(8888);while (true) {  System.out.println("execute 1\n");  Socket client = server.accept();  System.out.println("execute 2\n");  OutputStream out = client.getOutputStream();  System.out.println("execute 3\n");  String msg = "hello android";  out.write(msg.getBytes());  System.out.println("execute 4\n");client.close();   }  } catch (IOException e) { e.printStackTrace();}}}

  連接埠號碼:8888,等待用戶端串連!

然後看android用戶端的編碼:

因為操作線程不能在主線程,故:

 1 package com.hdc.sockettestclient; 2  3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.widget.TextView; 6  7 public class MainActivity extends Activity { 8     private TextView myTextView; 9 10     @Override11     protected void onCreate(Bundle savedInstanceState) {12         super.onCreate(savedInstanceState);13         setContentView(R.layout.activity_main);14 15         myTextView = (TextView) findViewById(R.id.textView1);16 17         new YunTheard(myTextView).start();18 19     }20 }
View Code

 

package com.hdc.sockettestclient;import java.io.IOException;import java.io.InputStream;import java.net.Socket;import java.net.UnknownHostException;import android.widget.TextView;public class YunTheard extends Thread {private TextView myTextView;public YunTheard(TextView myTextView) {super();this.myTextView = myTextView;}@Overridepublic void run() {try {myTextView.setText("0");Socket socket = new Socket("172.17.1.41", 8888);myTextView.setText("1");InputStream in = socket.getInputStream();byte[] buffer = new byte[in.available()];myTextView.setText("2");in.read(buffer);myTextView.setText("3");String msg = new String(buffer);myTextView.setText(msg);} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

  通訊成功後用戶端會顯示來自服務端的hello,android

java伺服器端與android用戶端的通訊

聯繫我們

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