Android uses socket to send JSON data demo

Source: Internet
Author: User


Client code:

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;/** * Socket client, * 1. Sir into JSON object * 2, convert JSON object to JSON String * 3, convert JSON string to byte array to write socket output stream * @author Yqq_coder * */public class Mainactivity extends Acti vity {private EditText et_name;private EditText et_age;private EditText et_sex;private String host= "172.21.133.15";// IP on the same LAN as the service-side phone, use port 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, "Information cannot be empty!!!", 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 string", result), New Thread (new Runnable () {@Overridepublic void run () {try {socket socket=new socket (inetaddres S.getbyname (host), 8155); OutputStream Os=socket.getoutputstream (); Os.write (Result.getbytes ()); Os.flush ();// Prevents the service-side read method from reading blocking socket.shutdownoutput ();} catch (Unknownhostexception e) {//Todo auto-generated catch Blocke.printstacktrace ()} catch (IOException e) {//Todo Aut O-generated catch Blocke.printstacktrace ();}}). Start ();}}

Service-Side code:

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;/** *  Socket Service Side * @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, $). Show (); btn.setenabled (true); if (msg.what==0x02) {new Thread (new Runnable () {@Overridepublic void run () {try {log.i ("Client Connection", "read data sent from client"); Nputstream Ins=msocket.getinputstream (); Bytearrayoutputstream os=new bytearrayoutputstream (); int len=0;byte[] Buffer=new byte[1024];while ((Len=ins.read ( Buffer)!=-1) {os.write (buffer);} The first step is to generate a JSON string format JSON object Jsonobject jsonobject=new jsonobject (os.tostring ());//The second step is to take a value from the JSON object if there are many JSON objects, You can use the JSON array string name= "name:" +jsonobject.getstring ("name"); String age= "Ages:" +jsonobject.getstring ("Age"); String sex= "Gender:" +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 () {@Override public void Run () {try {log.i ("Blocking, waiting for client Connection", "<<<<<<<<<"), if (server==null) {server=new ServerSocket (8155); } msocket=server.accept (); LOG.I ("Client connection succeeded", "<<<<<<<<< Client Connection succeeded"); Looper.prepare (); Message Message=message.obtain (); message.what=0x02;mhandler.sendmessage (message); Looper.loop ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}). Start ();}}


The second time to listen to the error:

04-28 12:55:52.841:w/system.err (8761): Java.net.BindException:bind failed:

Workaround:

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

demo:http://download.csdn.net/detail/u014600432/8640955

Android uses socket to send JSON data demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.