Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 利用socket 發送Json數據demo

android 利用socket 發送Json數據demo

編輯:關於Android編程

 

客戶端代碼:

 

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

	@Override
	protected 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() {
			@Override
			public 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 block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.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(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.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() {
					@Override
					public 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 block
							e.printStackTrace();
						}finally{
							
							if(mSocket!=null){
								try {
									mSocket.close();
									mSocket=null;
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								
							}
						}
						
					}
				}).start();
			}
			
		}
		
		
	};
	@Override
	protected 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() {
			
			@Override
			public 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 block
						e.printStackTrace();
					} 
				
				
				
			}
		}).start();
	}

	

}


 

第二次監聽時候報錯:

04-28 12:55:52.841: W/System.err(8761): java.net.BindException: bind failed:

解決辦法:

 

 if(server==null){
						 server=new ServerSocket(8155);
						 }

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved