Android App Development Basics (-----socket communication)

Source: Internet
Author: User

Link Address: http://www.cnblogs.com/lknlfy/archive/2012/03/03/2378669.html

I. Overview

network communication, whether in mobile phones or other devices are widely used, so mastering network programming is very necessary, and I think socket programming is the basis of network programming. Before entering the topic, first introduce several network knowledge, one: Socket programming has TCP and UDP two kinds, TCP is based on connection, and UDP is not connected; two: A TCP connection includes input and output two separate paths; three: the server must run before the client can communicate with it. Four: The client and the server use the same encoding method, or it will appear garbled. The following implementation in order to explain the convenience, and there is no multithreading method, so the communication process will block the UI thread , and only involves one-way communication (client-to-server), perfect program (multi-threaded, two-way communication) will be improved in the article again.

Second, the requirements

familiar with socket programming.

Third, the realization

New Project MyClient, modify the/res/layout/main.xml file, add a EditText and two buttons inside, complete the Main.xml file as follows:

1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:layout_width= "Fill_parent"
4 android:layout_height= "Fill_parent"
5 android:orientation= "Vertical" >
6
7 <edittext
8 android:id= "@+id/edittext"
9 android:layout_width= "Fill_parent"
Ten android:layout_height= "Wrap_content"
Android:hint= "Please enter what you want to send"
/>
13
<button
Android:id= "@+id/connectbutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Connection"
/>
20
<button
Android:id= "@+id/sendbutton"
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Send"
/>
27
28
</LinearLayout>

Next, modify the Myclientactivity.java file, define a socket object and a OutputStream object (for sending data), complete with the following:

1 package com.nan.client;
2
3 Import java.io.IOException;
4 Import Java.io.OutputStream;
5 Import java.io.UnsupportedEncodingException;
6 Import Java.net.Socket;
7 Import java.net.UnknownHostException;
8
9 Import android.app.Activity;
Ten import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Import Android.widget.Toast;
15
16
public class Myclientactivity extends Activity
18 {
Private EditText medittext = null;
Private Button Connectbutton = null;
Private Button Sendbutton = null;
22
Clientsocket-Private Socket = null;
Private OutputStream outstream = null;
25
26
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate)
30 {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
33
Medittext = (EditText) This.findviewbyid (R.id.edittext);
Connectbutton = (Button) This.findviewbyid (R.id.connectbutton);
Sendbutton = (Button) This.findviewbyid (R.id.sendbutton);
Panax Notoginseng sendbutton.setenabled (false);
38
39//Connection button monitoring
Connectbutton.setonclicklistener (New View.onclicklistener ()
41 {
42
@Override
The public void OnClick (View v)
45 {
$//TODO auto-generated method stub
Try
48 {
49//Instantiate the object and connect to the server
Clientsocket = new Socket ("183.41.101.71", 8888);
51}
The catch (Unknownhostexception e)
53 {
Wu//TODO auto-generated catch block
E.printstacktrace ();
56}
(IOException e)
58 {
+//TODO auto-generated catch block
E.printstacktrace ();
61}
62
Displaytoast ("Connection succeeded! ");
64
Connectbutton.setenabled (FALSE);
Sendbutton.setenabled (TRUE);
67}
68});
69
70//Send Data button monitor
Sendbutton.setonclicklistener (New View.onclicklistener ()
72 {
73
@Override
-public void OnClick (View v)
76 {
/TODO auto-generated Method stub
byte[] Msgbuffer = null;
79//Get Edittex's content
String text = Medittext.gettext (). toString ();
Bayi try {
82//Character encoding conversion
Msgbuffer = Text.getbytes ("GB2312");
(Unsupportedencodingexception E1) {
/TODO auto-generated Catch block
E1.printstacktrace ();
87}
88
89
try {
91//Get socket output stream
OutStream = Clientsocket.getoutputstream ();
IOException} catch (e) {
94//TODO auto-generated catch block
E.printstacktrace ();
96}
97
98
try {
100//Send data
101 Outstream.write (Msgbuffer);
102} catch (IOException e) {
103//TODO auto-generated catch block
104 E.printstacktrace ();
105}
106
107 Displaytoast ("sent successfully! ");
108}
109});
110
111
112}
113
114//Show Toast function
Displaytoast private void (String s)
116 {
117 Toast.maketext (this, S, Toast.length_short). Show ();
118}
119
120
121}

Then, the new project MyServer, also modify the/res/layout/main.xml file, as follows:

1 <?xml version= "1.0" encoding= "Utf-8"?>
2 <linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
3 android:layout_width= "Fill_parent"
4 android:layout_height= "Fill_parent"
5 android:orientation= "vertical" >

7 <textview
8 android:id= "@+id/textview"
9 android:layout_width= "Fill_parent"
Ten android:layout_height= "Wrap_content"
android:textsize= "15dip"
12
/>

</LinearLayout>

Modify the Myserveractivity.java file, it is relatively simple, the code has detailed comments, as follows:

1 package com.nan.server;
2
3 Import java.io.IOException;
4 Import Java.io.InputStream;
5 Import java.io.UnsupportedEncodingException;
6 Import Java.net.ServerSocket;
7 Import Java.net.Socket;
8
9 Import android.app.Activity;
Ten import Android.os.Bundle;
Import Android.widget.TextView;
12
13
public class Myserveractivity extends Activity
15 {
Private TextView Mtextview = null;
17
Private InputStream minputstream = null;
Private Socket clientsocket = null;
Private ServerSocket mserversocket = null;
21st
/** called when the activity is first created. */
@Override
public void OnCreate (Bundle savedinstancestate)
25 {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
28
Mtextview = (TextView) This.findviewbyid (R.id.textview);
30
try {
32//Instantiate the ServerSocket object and set the port number to 8888
Mserversocket = new ServerSocket (8888);
IOException} catch (e) {
//TODO auto-generated catch block
E.printstacktrace ();
37}
38
try {
40//Waiting for Client connection (blocking)
Clientsocket = Mserversocket.accept ();
* catch (IOException e) {
+//TODO auto-generated catch block
E.printstacktrace ();
45}
46
try {
48//Get socket input stream
Minputstream = Clientsocket.getinputstream ();
\ catch (IOException e) {
Wuyi//TODO auto-generated catch block
E.printstacktrace ();
53}
54
byte[] buf = new byte[512];
The String str = NULL;
57
try {
59//Read input data (block read)
Minputstream.read (BUF);
(IOException e) {
+//TODO auto-generated catch block
E.printstacktrace ();
64}
65
try {
67//Character encoding conversion
BUF str = new String ("GB2312"). Trim ();
Unsupportedencodingexception} catch (e) {
#//TODO auto-generated catch block
E.printstacktrace ();
72}
73//Display of received data
Mtextview.settext ("Data Received:" +STR);
75
76}
77
78}

Finally, the permissions are added to the Androidmainfest.xml files of both projects:

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

Here, the client and server programs are written, and the client program runs on the emulator:

To run the server program on a real machine:

Next, click on the client "Connect" button, enter some content and then click the "Send" button:

At this point the server-side situation is as follows:

Visible successfully received the data sent by the client.

Android App Development Basics (-----socket communication)

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.