android 利用socket 發送Json資料demo
用戶端代碼:
package com.yqq.jsonclienttest;import java.io.IOException;import java.io.OutputStream;import java.net.InetAddress;import java.net.Socket;import java.net.UnknownHostException;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.Toast;/** * 通訊端用戶端, * 1、先產生JSON對象 * 2、將JSON對象轉成JSON字串 * 3、將JSON字串轉成位元組數組寫入通訊端輸出資料流 * @author yqq_coder * */public class MainActivity extends Activity {private EditText et_name;private EditText et_age;private EditText et_sex;private String host=172.21.133.15;//同一個區域網路內作為服務端的手機的IP,使用連接埠8155@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);et_name=(EditText) findViewById(R.id.et_name);et_age=(EditText) findViewById(R.id.et_age);et_sex=(EditText) findViewById(R.id.et_sex);}public void submit(View v) throws JSONException{if(TextUtils.isEmpty(et_name.getText().toString().trim())||TextUtils.isEmpty(et_age.getText().toString().trim())||TextUtils.isEmpty(et_sex.getText().toString().trim())){Toast.makeText(MainActivity.this, 資訊不可為空!!!, 0).show();return;}JSONObject jsonObject=new JSONObject();jsonObject.put(name, et_name.getText().toString().trim());jsonObject.put(age, et_age.getText().toString().trim());jsonObject.put(sex, et_sex.getText().toString().trim());final String result=jsonObject.toString();Log.i(jSON字串, result);new Thread(new Runnable() {@Overridepublic void run() {try {Socket socket=new Socket(InetAddress.getByName(host), 8155);OutputStream os=socket.getOutputStream();os.write(result.getBytes());os.flush();//防止服務端read方法讀阻塞socket.shutdownOutput();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}}
服務端代碼:
package com.yqq.jsonclienttest1;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.UnknownHostException;import org.json.JSONException;import org.json.JSONObject;import com.yqq.jsonclienttest1.R;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.os.Message;import android.text.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;/** * 通訊端服務端 * @author yqq_coder * */public class MainActivity extends Activity {private Button btn; volatile Socket mSocket; ServerSocket server;private Handler mHandler=new Handler(){@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);if(msg.what==0x01){Toast.makeText(MainActivity.this,(String) msg.obj, 500).show();btn.setEnabled(true);}if(msg.what==0x02){new Thread(new Runnable() {@Overridepublic void run() {try { Log.i(用戶端串連, 讀取用戶端發來的資料);InputStream ins=mSocket.getInputStream();ByteArrayOutputStream os=new ByteArrayOutputStream();int len=0;byte[] buffer=new byte[1024];while((len=ins.read(buffer))!=-1){os.write(buffer);}//第一步,產生Json字串格式的JSON對象JSONObject jsonObject=new JSONObject(os.toString());//第二步,從JSON對象中取值如果JSON 對象較多,可以用json數組String name=姓名:+jsonObject.getString(name);String age=年齡:+jsonObject.getString(age);String sex=性別:+jsonObject.getString(sex);StringBuffer sb=new StringBuffer();sb.append(name);sb.append(age);sb.append(sex);Looper.prepare();Message message=Message.obtain();message.what=0X01;message.obj=sb.toString();mHandler.sendMessage(message);Looper.loop();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(mSocket!=null){try {mSocket.close();mSocket=null;} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}).start();}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn=(Button) findViewById(R.id.btn);}public void submit(View v) throws JSONException, IOException{btn.setEnabled(false); new Thread(new Runnable() {@Overridepublic void run() {try { Log.i(阻塞,等待用戶端串連, <<<<<<<<<); if(server==null){ server=new ServerSocket(8155); } mSocket=server.accept(); Log.i(用戶端串連成功, <<<<<<<<<用戶端串連成功);Looper.prepare();Message message=Message.obtain();message.what=0X02;mHandler.sendMessage(message);Looper.loop();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }}).start();}}
第二次監聽時候報錯:
04-28 12:55:52.841: W/System.err(8761): java.net.BindException: bind failed:
解決辦法:
if(server==null){ server=new ServerSocket(8155); }