服務器端:java代碼php
package com; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class server { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("接受串:"); try{ ServerSocket server=new ServerSocket(1116); while(true){ Socket socket=server.accept(); BufferedWriter writer=new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("dadasdsada"); writer.flush(); //清空緩存中的數據 writer.close(); } } catch(IOException e){ e.printStackTrace(); } } }
客戶端android代碼:java
package com; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; import com.android_clinent.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class client extends Activity{ Button btn; TextView txt; String line; String HOST="192.168.0.105"; int PORT=1116; public void onCreate(Bundle SavedInstanceState){ super.onCreate(SavedInstanceState); setContentView(R.layout.main); initControl(); } public void initControl(){ btn=(Button)findViewById(R.id.button1); txt=(TextView)findViewById(R.id.editText1); btn.setOnClickListener(new ReListener()); } class ReListener implements OnClickListener{ @Override public void onClick(View arg0) { //在android4.0以上的系統中,是不容許在主線程裏面去執行網絡相關的請求,不然會報錯:NetworkOnMainThreadException new Thread(){ public void run(){ // TODO Auto-generated method stub try{ Socket socket=new Socket(HOST,PORT); BufferedReader br=new BufferedReader( new InputStreamReader(socket.getInputStream())); line=br.readLine(); if(line!=null) { //不要在UI線程以外訪問Andoid的UI組件包, 用View.post(Runnable) txt.post(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub txt.setText(line); } }); }else { txt.setText("有問題"); } br.close(); } catch(UnknownHostException e){ e.getStackTrace(); } catch(IOException e){ e.getStackTrace(); } } }.start(); } } }
服務端運行結果:android
接受串:
客戶端android真機上運行結果:web
執行前:緩存
執行後:服務器
另外在配置文件中記得加上權限:<uses-permission android:name="android.permission.INTERNET">
測試的時候先啓動服務端,而後啓動客戶端,點擊按鈕就可獲取到服務端信息。這是在是一個灰常簡單的有關android socket的小例子,能夠初步對socket有個簡單的瞭解,這個筆記就先記到這裏!網絡
參考文章:http://www.apkbus.com/forum.php?mod=viewthread&tid=122400app