客户端代码:

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

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

更多相关文章

  1. 类和 Json对象
  2. Android(安卓)为Notification加上一个进度条
  3. android 获取网络上服务器图片
  4. android发送json并解析返回json
  5. Android控制台中运行Java程序
  6. android Dialog中SeekBar的使用方法
  7. Android中Parcelable接口用法
  8. Android(安卓)DOC文档分析——Dialog
  9. android 自定义TextView中Html超链接点击事件详解

随机推荐

  1. 确定记录出现的次数
  2. 整合Hadoop2.2.0+HBase0.96+Hive0.12+MyS
  3. linux下mysql配置文件my.cnf详解
  4. mysql获取某个范围内的随机数,写了个存储
  5. 吐槽:MySQL和Delphi2010的UTF8编码
  6. 无法运行查询:SQLSTATE [23000]:完整性约束
  7. 在woody上安装了mysql为什么没有开3306端
  8. 网易MySQL数据库工程师微专业学习笔记(十
  9. 用PHP比较PHP中的字符串
  10. Mysqlbackup&#160;3.9.0 企业级备份工具