Author: Ching
Original address: http://blog.csdn.net/qingdujun/article/details/39274055
Clients can typically use the socket's constructor to link to the specified server.
As shown below, the Android link is linked to the server, and the server sends a message to Android:
1) server-side
2) Android side
1) server-side
A small problem encountered during writing:java.net.BindException:Address already in Use:jvm_bind, the reasons for this problem are analyzed in the following ways:
①) Cause: The port is already occupied.
Solution: Change a port.
②) Reason: variable definition location problem (I don't know if this is the problem, maybe I started this problem, changed a few ports or not resolved, then I defined the variable outside, it solved)
Solution: Define the variables externally.
Package Dujun.king.javaee;import Java.io.outputstream;import Java.net.serversocket;import java.net.Socket;public Class Cserver {public static void main (string[] args) {//Create a ServerSocket to listen for the client socket's link request//natively IP: 169.254.49.31ServerSocket Ss=null; Socket s = null;outputstream OS = null;//takes the loop continuously to accept requests from the client while (true) {try {System.out.println ("Wait for the client's link ...."); ss = new S Erversocket (9527);//Whenever a client socket request is received, the server also generates a sockets = Ss.accept (); SYSTEM.OUT.PRINTLN ("Client has linked ....."); OS = S.getoutputstream (); Os.write ("Hello, get a message!"). GetBytes ("Utf-8"));//close the output stream, turn off Socketos.close (); S.close (); Ss.close ();} catch (Exception e) {e.printstacktrace ();}}}}
2) Android side
Writing process encountered a small problem, that is (I use the real machine) is not connected to the server, I thought that is not the problem of IP address, I have changed a number of useless (including My network after the IP 113.132.174.158, not connected to the IP 169.254.49.31).
Solution: Add an emulator without a real-computer emulation. (use: 169.254.49.31 test success, e.g.)
A) XML layout code:
<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:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin " android:paddingright=" @dimen/activity_horizontal_margin " android:paddingtop=" @dimen /activity_vertical_margin " tools:context=" client.dujun.king.tcp.MainActivity "> <edittext Android:id= "@+id/show" android:layout_width= "fill_parent" android:layout_height= "Wrap_content " Android:hint= ""/></relativelayout>
b) Mainactivity.java Code:
Package Client.dujun.king.tcp;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.socket;import Android.app.activity;import Android.os.bundle;import Android.view.menu;import Android.view.menuitem;import Android.widget.edittext;public class Mainactivity extends Activity {EditText show; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Show = (EditText) Findviewbyid (r.id.show); New Thread () {@Override public void run () {try {//Establish socket socket SOC connected to the remote server Ket = new Socket ("169.254.49.31", 9527); The input stream corresponding to the socket is packaged into BufferedReader bufferedreader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); For normal I/O operation String line = Br.readline (); Show.settext ("Data from the server:" +line); Br.close (); Socket.close ();} catch (Exception e) {E.printstacktracE ();} }}.start (); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio n Bar if it is present. Getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent Activity in Androidmanifest.xml. int id = item.getitemid (); if (id = = r.id.action_settings) {return true; } return super.onoptionsitemselected (item); }}c) Androidmainifest.xml permission setting code:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Client.dujun.king.tcp "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android:minsdkversion= "android:targetsdkversion="/><!--access to Internet rights--><uses-permission Android:name= "Android.permission.INTERNET"/> <application android:allowbackup= "true" android:icon= " @drawable/ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme "> <acti Vity android:name= ". Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest>
References: Crazy Android Handout (2nd edition) Li Gang authoring
Original address: http://blog.csdn.net/qingdujun/article/details/39274055
Android uses sockets for communication