Android uses socket to send Json data demo
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. convert a JSON object * 2. convert a JSON object to a JSON string * 3. convert a JSON string to a byte array and write it to the socket output stream * @ 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; // use port 8155 @ Overrideprotected void onCreate (Bundle savedInstanceState) as the IP address of the server's mobile phone in the same LAN) {super. onCreate (savedInstanceState); set ContentView (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. makeTe Xt (MainActivity. this, the information cannot be blank !!!, 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 (InetAddress. getByName (host), 8155); OutputStream OS = socket. getOutputStream (); OS. write (result. getBytes (); OS. flush (); // prevents the socket from being blocked by the server's read method. shutdownOutput ();} catch (UnknownHostException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}). start ();}}
Server 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. logoff; 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 server * @ 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 (Client connection, read data from the client); InputStream ins = mSocket. getInputStream (); Byt EArrayOutputStream 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 the Json object JSONObject jsonObject = new JSONObject (OS. toString (); // Step 2. If a large number of JSON objects are taken from the JSON object, you can use the json array String name = name: + jsonObject. getString (name); String age = age: + jsonObject. getString (age); String sex = Gender: + jsonObject. getString (sex); StringBuffer sb = new StringBuffer (); sb. append (name); sb. append (age); sb. append (sex); logoff. prepare (); Message message = Message. obtain (); message. w Hat = 0X01; message. obj = sb. toString (); mHandler. sendMessage (message); logoff. 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 (blocking, waiting for client connection, <); if (server = null) {server = new ServerSocket (8155);} mSocket = server. accept (); Log. I (Client Connection successful, <client connection successful); logoff. prepare (); Message message = Message. obtain (); message. what = 0X02; mHandler. sendMessage (message); logoff. loop ();} catch (Exception e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}). start ();}}
An error is reported during the second listener:
04-28 12:55:52. 841: W/System. err (8761): java.net. BindException: bind failed:
Solution:
if(server==null){ server=new ServerSocket(8155); }