Friday, 20 July 2012

Socket Programming in Android


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SocketProgramActivity1 extends Activity {
    /** Called when the activity is first created. */
private EditText sendText,RecievedText;
private Button SendBtn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sendText = (EditText)findViewById(R.id.editText1);
        RecievedText = (EditText)findViewById(R.id.editText2);
        SendBtn = (Button)findViewById(R.id.button1);
        SendBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Socket firstSocket  = null;

DataOutputStream dos = null;
DataInputStream dis = null;
try {
// here specify the server ip and the port number
   firstSocket = new Socket("ServerIp",portnumber);
// Create DataOutputStream to connect send data to the server
dos = new DataOutputStream(firstSocket.getOutputStream());
// Sending the data to the server
dos.writeUTF(sendText.getText().toString());
// Initialize DataInputStream to recieve the sent data
dis = new DataInputStream(firstSocket.getInputStream());
//set recieved text to the edit text
RecievedText.setText(dis.readUTF());

} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (firstSocket != null){
                    try {
                        //close socket connection after using it otherwise next time when u reconnect on  the same port
                        // it will throw error if you dont close it

                    firstSocket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

                if (dos != null){
                    try {
                        //close outputstream
                        dos.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if (dis != null){
                    try {
                        //close inputsteam
                        dis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
           
}

}
});
    }

}

the Manifest file is



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.scan.android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
 <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SocketProgramActivity1"
            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>


and the xml file is

<?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="enterText" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text">

        <requestFocus />

    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RecievedText" />


    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:inputType="text"/>

</LinearLayout>


1 comment:

  1. Hello.

    I tried to follow your code
    But it hangs
    I need to simply send a msg test to ip address 10.19.21.128
    with port no 8221

    But issue is that it gives me socket exception,

    Same thing i tried in java its working,


    My java code

    http://pastie.org/8656088

    Mine skype id is tushar1271921
    And Email : tusharsahni50@gmail.com

    Plz help and try to solve my issue and tell where exactly i am doing wrong?

    Thanks
    Tushar

    ReplyDelete