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

	@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);
						 }

demo下载地址:http://download.csdn.net/detail/u014600432/8640955

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。