Realization of Android and Scoket communication under LAN

Source: Internet
Author: User

Because recent lab projects require that Android app data be sent to Winsock for storage under a local area network, this is a simple learning. PC side because it is another classmate to do, so do not explain.

On the Android side, first add the permissions:

    <uses-permission android:name= "Android.permission.INTERNET"/>  

The app interface is then simply designed--main.xml:

    <linearlayout android:orientation= "Horizontal" android:layout_width= "Match_parent"                  android:layout_height= "Wrap_content" > <!--define a text box that is used to receive user input--<edittext Android:id= "@+id/input" android:layout_width= "280DP" Android:layout_heig                  ht= "Wrap_content" android:inputtype= ""/> <button android:id= "@+id/send" Android:layout_width= "Match_parent" android:layout_height= "Wrap_content" Android:padd Ingstart= "8DP" android:text= "@string/send"/> </LinearLayout> <!--define a text box that Used to display information from the server--<textview android:id= "@+id/show" android:layout_width= "Match_par Ent "android:layout_height=" match_parent "android:gravity=" Top "android:background= "#ffff" andRoid:textsize= "14SP" android:textcolor= "#f000"/>   

The interface is as follows:

Create Clientthread.java to enable data transfer under LAN:

public class Clientthread implements Runnable{private Socket s;//defines the Handler object that sends messages to the UI thread private Handler handler;// The Handler object that defines the message that receives the UI thread public Handler revhandler;//the input stream corresponding to the socket processed by the thread bufferedreader br = Null;outputstream OS = null; Public Clientthread (Handler Handler) {this.handler = Handler;} public void Run () {try{s = new Socket ("192.168.1.133", 8040); br = new BufferedReader (New InputStreamReader ( S.getinputstream ())); OS = S.getoutputstream ();//Start a sub thread to read the server response data New Thread () {@Overridepublic void run () {String Content = null;//Constantly reads the contents of the socket input stream Try{while ((content = Br.readline ()) = null) {///each time the data from the server is read, send a message notifier// The interface displays the data message msg = new Message (); msg.what = 0x123;msg.obj = Content.tostring (); Handler.sendmessage (msg);}} catch (IOException e) {e.printstacktrace ();}}}. Start ();//Initialize Looperlooper.prepare () for current thread,//Create Revhandler Object revhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//receives the user input data from the UI thread if (msg.what = = 0x345) {//writes the user's input in the text box to the network Try{os.write (Msg.obj.toStriNg () + "\ r \ n"). GetBytes ("Utf-8")); catch (Exception e) {e.printstacktrace ();}}}};/ /start Looperlooper.loop ();} catch (Sockettimeoutexception E1) {System.out.println ("Network connection timed out!! ");} catch (Exception e) {e.printstacktrace ();}}}

  Finally create Mainactivity.java to implement the acquisition of content sent in the app, and other functions:

The public class Mainactivity extends activity{//defines two text boxes on the interface edittext input; TextView show;//defines a button on the interface buttons send; Handler handler;//defines a child thread Clientthread clientthread that communicates with the server; @Overridepublic void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.main); input = (EditText) Findviewbyid (r.id.input); send = (Button) Findviewbyid (r.id.send); show = (TextView) Findviewbyid (r.id.show); handler = new Handler ()//②{@ overridepublic void Handlemessage (Message msg) {//If the message is from a child thread if (msg.what = = 0x123) {//Append read content to the text box show.append ("\ n" + Msg.obj.toString ());}}; Clientthread = new Clientthread (handler);//client initiates Clientthread thread creates a network connection, reads data from the server new Thread (Clientthread). Start (); ①send.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {try{//When the user presses the Send button, The data entered by the user is encapsulated into message//and then sent to the child thread by handlermessage msg = new Message (), msg.what = 0x345;msg.obj = Input.gettext (). toString (); ClientThread.revHandler.sendMessage (msg);//Empty input text box Input.settext ("");}catch (Exception e) {e.printstacktrace ();}});}} 

In this way, we realized the functions we wanted to transfer data to the PC.

Realization of Android and Scoket communication under LAN

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.