1, in order to develop "world coin" this Android mobile phone project, need to use socket programming.
2. The world currency is a virtual currency similar to Bitcoin.
3, in order to earn CSDN C currency, need to write a blog.
4, simply will debug socket project sent to share with friends.
Gossip Hugh, directly on the code, first is the definition of the string:
<?XML version= "1.0" encoding= "Utf-8"?><resources> <string name= "App_name" >xyzsocket</string > <string name= "Hello_world" >hello world!</string> <string name= "Action_settings" > settings</string> <string name= "Ipaddr_str" > Native ip:</string> <string name= " Serveripaddr_str "> Server ip:</string> <string name=" Server_str "> Set as Service side </string> < String name= "Client_str" > Connect as Client </string> <string name= "Mymachine_str" > Native is </string> <string name= "Send_str" > Send </string> <string name= "Online_str" >0 online </string> <string name= "Threeline_str" > 1th line \ 2nd line \ 3rd line \n</string> </resources>
Next is the XML file:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: context= "Com.example.xyzsocket.mainactivity$placeholderfragment" > <relativelayout android:id= "@+id/re Lativelayout_1 "android:layout_width=" match_parent "android:layout_height=" Wrap_content "> <textview android:id= "@+id/ipaddr_label_1" android:layout_width= "Wrap_content" Android:layout_heig ht= "Wrap_content" android:layout_centervertical= "true" android:text= "@string/ipaddr_str"/> <edittext android:id= "@+id/myipaddr_edit" aNdroid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:layout_torightof= "@+id/ipadd R_label_1 "android:layout_toleftof=" @+id/noline_label_1 "/> <textview android:id=" @+id/o Nline_label_1 "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layou T_alignparentright= "true" android:layout_centervertical= "true" android:text= "@string/online_str"/&G T </RelativeLayout> <relativelayout android:id= "@+id/relativelayout_2" Android:layout_width= "M Atch_parent "android:layout_height=" wrap_content "android:layout_below=" @+id/relativelayout_1 "> <edittext android:id= "@+id/server_receiver" android:layout_width= "Match_parent" Android:layo ut_height= "Wrap_content" android:maxlines= "3" android:text= "@string/threeline_str"/> & Lt;/relativelayout> <relativelayout android:id= "@+id/relativelayout_3" android:layout_width= "match_parent "Android:layout_height=" wrap_content "android:layout_below=" @+id/relativelayout_2 "> & Lt TextView android:id= "@+id/ipaddr_label_2" android:layout_width= "Wrap_content" android:layout_height= " Wrap_content "android:layout_centervertical=" true "android:text=" @string/serveripaddr_str "/> <edittext android:id= "@+id/serveripaddr_edit" android:layout_width= "Match_parent" Android:layo ut_height= "Wrap_content" android:layout_torightof= "@+id/ipaddr_label_2" android:layout_toleftof= "@+id/server Ipaddr_check "/> <checkbox android:id=" @+id/serveripaddr_check "android:layout_width=" WR Ap_content "android:layout_height=" Wrap_content "android:layout_alignparentright=" true "android:layou T_centervertical= "TruE "android:text=" @string/mymachine_str "/> </RelativeLayout> <relativelayout Android:id= "@+id/relativelayout_4" android:layout_width= "match_parent" android:layout_height= "Wrap_con Tent "android:layout_below=" @+id/relativelayout_3 "> <edittext android:id=" @+id/send_mes Sage "android:layout_width=" match_parent "android:layout_height=" Wrap_content "Android:layout_tolefto f= "@+id/butt_send"/> <button android:id= "@+id/butt_send" android:layout_width= " Wrap_content "android:layout_height=" Wrap_content "android:layout_alignparentright=" true "Android:tex t= "@string/send_str"/> <linearlayout android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:layout_centerhorizontal= "true" android:orientation= "Horizontal" an Droid:layout_below= "@+id/send_message "> <button android:id=" @+id/butt_server "Android:layout_wi Dth= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/server_str" Android:lay out_below= "@+id/send_message"/> <button android:id= "@+id/butt_client" Andro Id:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/client_str" android:layout_below= "@+id/send_message"/> </LinearLayout> </relativela Yout> </RelativeLayout>
The most basic is the code:
Package Com.example.xyzsocket;import Java.io.datainputstream;import Java.io.dataoutputstream;import Java.io.ioexception;import Java.net.inetaddress;import Java.net.serversocket;import Java.net.Socket;import Java.net.unknownhostexception;import Java.util.arraylist;import Android.support.v7.app.actionbaractivity;import Android.support.v7.app.actionbar;import Android.support.v4.app.fragment;import Android.content.Context;import Android.net.wifi.wifiinfo;import Android.net.wifi.wifimanager;import Android.os.bundle;import Android.os.Handler; Import Android.os.message;import android.util.log;import android.view.layoutinflater;import android.view.Menu; Import Android.view.menuitem;import android.view.view;import android.view.viewgroup;import Android.widget.Button; Import Android.widget.checkbox;import Android.widget.compoundbutton;import Android.widget.edittext;import Android.widget.textview;import Android.os.build;public class Mainactivity extends Actionbaractivity {private EditText ET01 = null;p rivate EditText et02 = null;private EditText et03 = null;private EditText et04 = null;private Button Bn01 = null;private Button bn02 = null;private button bn03 = null;private CheckBox cb01 = null;private TextView tv01 = null; @Overrideprotecte d void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); if (savedinstancestate = = null) {Getsupportfragmentmanager (). BeginTransaction (). Add (R.id.container, new Placeholderfragment ()). commit ();}} Private String Inttoip (int i) {return (I & 0xFF) + "." + ((i>>8) & 0xFF) + "." + ((i>>16) & 0xFF) + "." + ((i>>24) & 0xFF);} @Overridepublic void Onwindowfocuschanged (Boolean hasfocus) {//TODO auto-generated method Stubsuper.onwindowfocuschanged (Hasfocus); if (et01 = = null) {et01 = (EditText) Findviewbyid (R.id.myipaddr_edit); if ( Et01! = null) {Wifimanager Wifimanager = (wifimanager) getsystemservice (Context.wifi_service); Wifimanager.iswifienabled ()) {Wifimanager.Setwifienabled (TRUE);} Wifiinfo wifiinfo = Wifimanager.getconnectioninfo (); int ipAddress = Wifiinfo.getipaddress (); Et01.settext (IntToIp ( ipAddress));}} if (et02 = = null) {et02 = (EditText) Findviewbyid (r.id.server_receiver); if (et02! = null) {}}if (et03 = = null) {et03 = (Edit Text) Findviewbyid (R.id.serveripaddr_edit), if (et03! = null) {}}if (et04 = = null) {et04 = (EditText) Findviewbyid ( R.id.send_message); if (et04! = null) {et04.setenabled (false);}} if (Bn01 = = null) {Bn01 = (Button) Findviewbyid (R.id.butt_server), if (bn01! = null) {Bn01.setonclicklistener (new View.oncl Icklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stub new Thread () {@Overrid e public void Run () {//Network access code is placed here Server (); }}.start (); }});}} if (bn02 = = null) {bn02 = (Button) Findviewbyid (r.id.butt_client), if (bn02! = null) {Bn02.setonclicklistener (new View.oncl Icklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated MethoD stub new Thread () {@Override public void run () {//network access code put here by client (); }}.start (); }});}} if (bn03 = = null) {bn03 = (Button) Findviewbyid (r.id.butt_send), if (bn03! = null) {Bn03.setonclicklistener (new view.onclic Klistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stub new Thread () {@Override public void Run () {//network access code put here sendmsg (); }}.start (); }}); bn03.setenabled (false);}} if (CB01 = = null) {CB01 = (CheckBox) Findviewbyid (R.id.serveripaddr_check); if (cb01! = null) {Cb01.setoncheckedchangelist Ener (New Compoundbutton.oncheckedchangelistener () {@Overridepublic void oncheckedchanged (Compoundbutton buttonview, Boolean isChecked) {//TODO auto-generated method Stubmessage msg = new Message (); msg.arg1 = Ischecked?1:0;msg.what = 103; Handler.sendmessage (msg);}});}} if (TV01 = = null) {TV01 = (TextView) Findviewbyid (R.id.online_label_1); if (tv01! = Null) {}}} @Overridepublic Boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action Bar if It is Present.getmenuinflater (). Inflate (R.menu.main, menu); return true;} @Overridepublic boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar will//automatically handle clicks on the Home/up button so long//as you specify a parent activity in and RoidManifest.xml.int id = item.getitemid (); if (id = = r.id.action_settings) {return true;} return super.onoptionsitemselected (item);} /** * A placeholder fragment containing a simple view. */public Static class Placeholderfragment extends Fragment {public placeholderfragment () {} @Overridepublic View Oncreateview (Layoutinflater inflater, ViewGroup container,bundle savedinstancestate) {View RootView = inflater.inflate (R.layout.fragment_main, Container,false); return rootview;}} Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO Auto-generAted method Stubsuper.handlemessage (msg); Myhandlemessage (msg);}; private void Myhandlemessage (Message msg) {switch (msg.what) {case 101:bn01.settext ("Server Abort"); Break;case 102:bn01.sett Ext (getString (R.STRING.SERVER_STR)); Break;case 103:if (msg.arg1>0) {Et03.settext (Et01.gettext (). toString ());} Break;case 104:bn02.settext (msg.arg1>0? ") Client Abort ": getString (R.STRING.CLIENT_STR)); bn03.setenabled (msg.arg1>0); et04.setenabled (msg.arg1>0); break; Case 110:string str = Et02.gettext (). toString (), int i = Str.indexof ("\ n"), if (i>0) {str = str.substring (i+1);} str + = (string) msg.obj;str + = "\ n"; et02.settext (str); Break;case 111:log.i ("DEBUG", "Client Received:" + (String) msg.obj); Case 112:LOG.I ("DEBUG", "Server aborted!!!"); Tv01.settext ("" + list.size () + "online"); Bn02.settext (GetString (R.STRING.CLIENT_STR)); bn03.setenabled (false); Et04.setenabled (false); Break;case 113:log.i ("DEBUG", "Client exited!!!"); Tv01.settext ("" + list.size () + "online"), Break;case 114:tv01.settext ("" + list.size () + "online"); ServerSocket asErversocket = null; ArrayList list = new ArrayList (); private void Server () {Myserverthread thread;if (aserversocket! = null) {try{aserversocket.close (); aserversocket = null;} catch (IOException e) {e.printstacktrace ();} if (Bn01! = null) {message msg = new Message (); Msg.what = 102; Handler.sendmessage (msg); }return;} try {aserversocket = new ServerSocket (55555); LOG.I ("DEBUG", "Already listen 55555 port."); } catch (Exception e) {e.printstacktrace (); } if (aserversocket = = null) {LOG.I ("DEBUG", "Listen failed!!!"); Return } log.i ("DEBUG", "Listen successfully!!!"); if (Bn01! = null) {message msg = new Message (); Msg.what = 101; Handler.sendmessage (msg); } int num = 0; while (Num <) {Socket asessionsoket = null; try {log.i ("DEBUG", "Pre-listening!!"); Asessionsoket = Aserversocket.accePT (); LOG.I ("DEBUG", "After listening!!"); thread = new Myserverthread (asessionsoket); Thread.Start (); Message msg = new Message (); Msg.what = 114; Handler.sendmessage (msg); } catch (IOException E1) {//TODO auto-generated catch block E1.printstacktrace (); LOG.I ("DEBUG", "Server manually aborted!!!"); for (int i=0;i<list.size (); i++) {socket s = (socket) list.get (i); try{S.close (); }catch (IOException e) {e.printstacktrace (); }} list.clear (); Break num = List.size (); LOG.I ("DEBUG", "socket count =" + num); }} class Myserverthread extends Thread {public Socket asessionsoket = null; Public myserverthread (socket socket) {asessionsoket = socket; List.add (socket); public void Run () {DataInputStream adatainput = null; DataOutputStream adataoutput = null; try {adatainput = NEW DataInputStream (Asessionsoket.getinputstream ()); Adataoutput = new DataOutputStream (Asessionsoket.getoutputstream ()); while (true) {log.i ("DEBUG", "Server received before!!"); String str = ADATAINPUT.READUTF (); Read Msg. LOG.I ("DEBUG", "After Server received!!"); Message msg = new Message (); msg.obj = Str;msg.what = 110;handler.sendmessage (msg); Adataoutput.writeutf ("OK:" + str);}} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();} finally {try {if (adatain Put! = null) adatainput.close (); if (adataoutput! = null) adataoutput.close (); List.remove (Asessionsoket); Asessionsoket.close ();//Exit Here is the client actively disconnecting message msg = new Message (); msg.what = 113;handler.sendmessage (msg);} catch (Exception E2) {e2.printstacktrace (); }}}}socket Clientsocket = null;private void Client () {Message msg;if (clientsocket! = null) {Try{clientsocket.clo Se (); clientsocket = null;} catch (IOException e) {e.printstacktrace (); return;} msg = new Message (); Msg.what = 104; MSG.ARG1 = 0; Handler.sendmessage (msg); return;} InetAddress serveraddr;try {serveraddr = Inetaddress.getbyname (Et03.gettext (). toString ()); LOG.D ("DEBUG", "c:connecting ..."); /Get connection to server Clientsocket = new Socket (serveraddr, 55555);} catch (Unknownhostexception E1) {//TODO auto-generated catch block E1.printstacktrace ();} catch (IOE Xception e) {//TODO auto-generated catch block E.printstacktrace ();} if (Clientsocket = = null) {LOG.I ("DEBUG", "Connection Failed!!!"); return;} if (bn03! = null) {msg = new Message (); Msg.what = 104; MSG.ARG1 = 1; Handler.sendmessage (msg); }myclientthread thread = new Myclientthread (clientsocket); Thread.Start (); } class Myclientthread extends Thread {public Socket asessionsoket = null; Public myclientthread (socket socket) {asessionsoket = socket; public void Run () {DataInputStream adatainput = null; try {adatainput = New DataInputStream (Asessionsoket.getinputstream ()); while (true) {log.i ("DEBUG", "Client received before!!"); String str = ADATAINPUT.READUTF (); LOG.I ("DEBUG", "After client received!!"); Message msg = new Message (); msg.obj = Str;msg.what = 111;handler.sendmessage (msg);} } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); Message msg = new Message (); msg.what = 112;handler.sendmessage (msg);} Finally {try {if (adatainput! = null) adatainput.close (); Asessionsoket.close ();} catch (Exception E2) {E2.printstacktra CE (); }}}}private void Sendmsg () {DataOutputStream adataoutput = null; String message = Et04.gettext (). toString (); if (Message.isempty ()) {return; }try {log.i ("DEBUG", "c:sending: '" + Message + "'"); adataoutput = new DataOutputStream (Clientsocket.getoutputstream ( )); Adataoutput.writeutf (message);} catch (Exception e) {e.printstacktrace ();} finally {}}}
Don't forget to join the permissions:
<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission> < Uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission> < Uses-permission android:name= "Android.permission.WAKE_LOCK" ></uses-permission><uses-permission Android:name= "Android.permission.INTERNET" ></uses-permission>
Finally, simply say how to use:
1, the software self-detection to their own WiFi IP address.
2, a machine can play the server and client at the same time.
3. Other machines can log on to the same server.
Network communication. It's so simple.
World Currency: The Android Socket Communication programming technology used in the test