Basic Idea of socket programming in Android

Source: Internet
Author: User

After studying Android for a period of time, I looked back at socket programming in Android today and found that socket programming is not very difficult. I sorted out socket programming in Android and provided our general socket steps.

1. socket programming is divided into server and client. First, a server must be established for the client to connect. The following describes how to create a server program:

1. First create a serversocket object and have the serversocket listen on a port number;

2. Call the accept () method of the serversocket object;

3. Obtain the inputstream object from the socket;

4. Define a byte buffer array to store data sent from the client;

5. Read the data sent from the client from inputstream.

The basic idea is as shown in the preceding figure. The following shows the source code comparison.

First, give the layout:

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "@ string/Hello"/> <button Android: Id = "@ + ID/startlistener" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "Start listening thread"/> </linearlayout>



The following Java source code:

Package COM. android. WWW; import Java. io. ioexception; import Java. io. inputstream; import java.net. serversocket; import java.net. socket; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. button; public class socketdemo extends activity {/** called when the activity is first created. */private button startbutton = NULL; @ override public void oncreate (bundle S Avedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); startbutton = (button) findviewbyid (R. id. startlistener); startbutton. setonclicklistener (New button. onclicklistener () {public void onclick (view v) {// todo auto-generated method stubnew serverthread (). start () ;}}) ;}class serverthread extends thread {public void run () {serversocket = NULL; try {// 1. Create a second Erversocket object, and let this socket listen to serversocket = new serversocket (4567) on port 6789; // 2. Call the serversocket accept () method, accept the request Socket socket = serversocket sent by the client. accept (); // 3. Obtain inputstream object inputstream = socket from the socket. getinputstream (); // 4. Define a byte buffer array to store the data sent from the client. byte buffer [] = new byte [1024*4]; int temp = 0; // 5. Read the data sent by the client from inputstream while (temp = inputstream. read (buffer ))! =-1) {system. out. println (new string (buffer, 0, temp) ;}} catch (ioexception e) {e. printstacktrace ();} finally {try {serversocket. close ();} catch (ioexception e) {e. printstacktrace ();}}}}}

To make the program run smoothly, you must declare the permission in the androidmanifest. xml file (Green bold part)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.www"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="8" />
       <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
       <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
       <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
       <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
       <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SocketDemo"
            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>


Note: The above programs can run correctly only on real mobile phones.

II. The following are the basic ideas for establishing a client program:

The client is written in Java and runs directly on the computer. The steps are the same as those for running j2se.

1. Create a socket object and specify the IP address and port number of the server. What is different from the IP address of the server is provided here. Because the server side is the object we want to communicate;

2. Obtain outputstream from the socket;

3. Define a buffer array to store the data to be sent;

4. Send data from the byte buffer array from outputstream.

Package COM. android. WWW; import Java. io. fileinputstream; import Java. io. inputstream; import Java. io. outputstream; import java.net. socket; public class tcpclient {public static void main (string [] ARGs) {// todo auto-generated method stubtry {// 1. Create a socket object, specify the IP address and port number of the server. // you can use the ipconfig command in the command line to obtain Socket socket = new socket ("192.168.159.10", 6789); // here, I use inputstream to read files on the hard disk and can send the file inputstream inputstrea. M = new fileinputstream ("D: // Android/hello.txt"); // 2. Obtain outputstreamoutputstream outputstream = socket from the socket. getoutputstream (); // 3 bytes defines the number of node buffers for storing the data read from hello.txt byte buffer [] = new byte [4*1024]; int temp = 0; // 4. Send the data of the byte buffer array from outputstream to while (temp = inputstream. read (buffer ))! =-1) {outputstream. Write (buffer, 0, temp) ;}outputstream. Flush () ;}catch (exception e) {e. printstacktrace ();}}}


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.