標籤:
伺服器端的工作非常簡單,建立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用戶端的通訊