The way that the client of Android programming communicates with the server via socket

Source: Internet
Author: User
Tags getmessage readline socket

the way that the client of Android programming communicates with the server via socket

This article is an example of how the client of Android programming communicates with the server via a socket. Share to everyone for your reference, specific as follows:

The following is a demo,android client communicates with the server through a socket.

Since Android can completely use java.io.* and java.net.* packages, the logical part is virtually indistinguishable from J2SE. Just the UI code is different.

The Android client communicates with the server through a socket with 5 steps:

(1) The socket is instantiated via IP address and port, and the connection server is requested;

The code is as follows:

Socket = new Socket ("10.14.114.127", 54321); ip:10.14.114.127, Port 54321

(2) Get the socket stream to read and write, and wrap the stream into Bufferwriter or printwriter

The code is as follows:

PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream)), true);

Here are three classes: Socket.getoutputstream get socket output byte throttling, OutputStreamWriter is a stream of bytes to the character streams conversion bridge, Bufferwriter is the character streams, and then packaged into PrintWriter.

(3) Read and write to the socket

The code is as follows:

OUT.PRINTLN (message);

(4) Close the open stream

The code is as follows:

Out.close ();

The complete engineering code is as follows:

Package com.yarin.android.Examples_08_04;

Import Java.io.BufferedReader;

Import Java.io.BufferedWriter;

Import Java.io.InputStreamReader;

Import Java.io.OutputStreamWriter;

Import Java.io.PrintWriter;

Import Java.net.Socket;

Import android.app.Activity;

Import Android.os.Bundle;

Import Android.util.Log;

Import Android.view.View;

Import Android.view.View.OnClickListener;

Import Android.widget.Button;

Import Android.widget.EditText;

Import Android.widget.TextView;

public class Activity01 extends activity

{

Private final String Debug_tag = "Activity01";

Private TextView Mtextview = null;

Private EditText medittext = null;

Private Button Mbutton = null;

/** called the activity is a. */

@Override

public void OnCreate (Bundle savedinstancestate)

{

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

Mbutton = (Button) Findviewbyid (R.ID.BUTTON01);

Mtextview = (TextView) Findviewbyid (R.ID.TEXTVIEW01);

Medittext = (edittext) Findviewbyid (r.id.edittext01);

Landing

Mbutton.setonclicklistener (New Onclicklistener ()

{

public void OnClick (View v)

{

Socket socket = NULL;

String message = Medittext.gettext (). toString () + "/r/n";

Try

{

Create a socket

Socket = new Socket ("192.168.1.110", 54321);

Socket = new Socket ("10.14.114.127", 54321); ip:10.14.114.127, Port 54321

Sending messages to the server

PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Socket.getoutputstream)), true);

OUT.PRINTLN (message);

Receiving messages from the server

BufferedReader br = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));

String msg = Br.readline ();

if (msg!= null)

{

Mtextview.settext (msg);

}

Else

{

Mtextview.settext ("Data Error!");

}

Close the stream

Out.close ();

Br.close ();

Close socket

Socket.close ();

}

catch (Exception e)

{

Todo:handle exception

LOG.E (Debug_tag, e.tostring ());

}

}

});

}

}

Layout file Main.xml

android:orientation= "Vertical"

Android:layout_width= "Fill_parent"

android:layout_height= "Fill_parent"

>

Android:id= "@+id/textview01"

Android:layout_width= "Fill_parent"

android:layout_height= "Wrap_content"

Android:text= "This shows the information received from the server."

/>

Android:id= "@+id/edittext01"

android:text= "Enter what you want to send"

Android:layout_width= "Fill_parent"

android:layout_height= "Wrap_content" >

Android:id= "@+id/button01"

Android:layout_width= "Fill_parent"

android:layout_height= "Wrap_content"

android:text= "Send"

/>

Androidmanifest.xml files are as follows

Package= "Com.yarin.android.Examples_08_04"

Android:versioncode= "1"

Android:versionname= "1.0" >

Android:label= "@string/app_name" >

And of course, there's the server-side code.

Package com.yarin.android.Examples_08_04;

Import Java.io.BufferedReader;

Import Java.io.BufferedWriter;

Import Java.io.InputStreamReader;

Import Java.io.OutputStreamWriter;

Import Java.io.PrintWriter;

Import Java.net.ServerSocket;

Import Java.net.Socket;

public class Server implements Runnable

{

public void Run ()

{

Try

{

Create ServerSocket

ServerSocket serversocket = new ServerSocket (54321);

while (true)

{

Accept client Requests

Socket client = Serversocket.accept ();

System.out.println ("accept");

Try

{

Receive client messages

BufferedReader in = new BufferedReader (New InputStreamReader (Client.getinputstream ()));

String str = in.readline ();

System.out.println ("read:" + str);

Sending messages to the server

PrintWriter out = new PrintWriter (new BufferedWriter (New OutputStreamWriter (Client.getoutputstream)), true);

OUT.PRINTLN ("Server Message");

Close the stream

Out.close ();

In.close ();

}

catch (Exception e)

{

System.out.println (E.getmessage ());

E.printstacktrace ();

}

Finally

{

Shut down

Client.close ();

System.out.println ("close");

}

}

}

catch (Exception e)

{

System.out.println (E.getmessage ());

}

}

Main function, turn on server

public static void Main (String a[])

{

Thread desktopserverthread = new Thread (new Server ());

Desktopserverthread.start ();

}

}

Open the server code first

Java Server can

Then start the Android emulator. Run results

This is the Android client. Enter 12345, click Send:

This is the message received from the server side

Related Article

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.