Android ioexception in socket

Android-ioexception-in-socket-featured.png

socket programming in android

Lets see how to deal with socker programming , but its very easy if you already have done with java..

for undersating purpose we make small but interesting app ..in which android devices talks with your system through socket

So we make two projects

(1) simple in java which acts as server [your system]
(2) second for your devices which acts as client [your android device]

Lets make server…..

we will use ServerSocket class and it will listen @port no 8889 for any request from client side

thats it!!

package com.myserver.demo;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {

/**
* This is server class which accepts all request through device and search for it…..
* @param args
*/
private static boolean flag=true;

public static void main(String[] args){
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;

try {
serverSocket = new ServerSocket(8889); //port number
System.out.println(“Listening :on port no 8889″);
}catch (BindException e ) {
System.out.println(“port is already used by some1″);
flag=false;
}
catch (IOException e) {
flag=false;
e.printStackTrace();
}
System.out.println(“value of flag…..” + flag);
while(flag){
try {
socket = serverSocket.accept(); //accept client connection
dataInputStream = new DataInputStream(socket.getInputStream()); //read from client through inputstream
dataOutputStream = new DataOutputStream(socket.getOutputStream());//write to stream through putputstream
System.out.println(“ip: ” + socket.getInetAddress()); //ip of client
System.out.println(“message: ” + dataInputStream.readUTF()); // read msg from client device
String str=null;
do{
System.out.println(“##################send message to #########”);

java.util.Scanner sc = new java.util.Scanner(System.in);

dataOutputStream.writeUTF(sc.nextLine());//write msg to stream client
System.out.println(“################## message sent to device #########”);
System.out.println(“################## again want to send msg?? press y or n #########”);
java.util.Scanner sc1 = new java.util.Scanner(System.in);
String s=sc.nextLine();

}while(str.equalsIgnoreCase(“y”));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= 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
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

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

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

}

Lets handle client side sitution,,,

here you have to enter
(1) server ip address
(2) port no on which it will be listening
(3) write some msg to send to server /also receive from server

we will use socket class .

Socket socket = new Socket(“192.168.18.1″,8889);

some usefull methods:–

socket.getOutputStream()// to write some msg to server
socket.getInputStream()// to receive some msg from server

package com.demo.searchit;

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.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SearchMyDevice extends Activity {

private EditText textOut; //write msg
private TextView textIn; //show received msg
private EditText ipaddressEdt; //enter ip address of server
private EditText portno; //port no

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ipaddressEdt = (EditText)findViewById(R.id.EditText01);
portno=(EditText)findViewById(R.id.EditText02);
textOut = (EditText)findViewById(R.id.messageedt);
Button buttonSend = (Button)findViewById(R.id.connecttoserver);
textIn = (TextView)findViewById(R.id.TextView01);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}

Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View arg0) {

//plz do socket connection in thread …as i have not done due to time constraint ,,
//it is good practice to do network connection in seperate thread instread of main thread
//otherwise it will show ANR[application not responding] dialog
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;

try {
socket = new Socket(ipaddressEdt.getText().toString().trim(), Integer.parseInt(portno.getText().toString().trim()));

dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
} catch (UnknownHostException e) {
//if specified ip address is not found in the network
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != 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

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

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

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

AndroidManifest.xml for layout….


package=”com.demo.searchit”
android:versionCode=”1″
android:versionName=”1.0″>

android:label=”@string/app_name”>






Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>