android: file transfer through sockets - android

hi i am trying to send a file through sockets in an android messenger. for some reason its not working. at times it does output a file but transfers no bytes that is the output file is of 0 bytes and sometimes the output or the received file is of 57 bytes precisely. following the code where i actually send the file :
public boolean sendFile(String ip, int port) {
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
filesize = (int) f.length();
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
FileInputStream fileIn = new FileInputStream(f);
Log.i("SocketOP", "sendFILE-2");
byte [] buffer = new byte [filesize];
int bytesRead =0;
while ((bytesRead = fileIn.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.flush();
out.close();
fileIn.close();
Log.i("SocketOP", "sendFILE-3");
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
this is where i send the inputstream to the receivefile method :
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket) {
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
//PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
InputStream is=clientSocket.getInputStream();
if (inputLine.contains("Text") == true) {
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");
} else if (inputLine.contains("Text") == false) {
Log.i("SocketOP","filee");
appManager.fileReceived(is);
} else {
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
}
}
}
and finally this is how i receive the file :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
//int filesize=6022386; // filesize temporary hardcoded
int bytesRead;
final byte[] aByte = new byte[is.toString().length()];
if (is!= null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
the following is the complete socketoperator file :
package hardy.scl.communication;
import hardy.scl.interfaces.IAppManager;
import hardy.scl.interfaces.ISocketOperator;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://10.10.10.100/chippers/";
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
public int filesize ;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
Socket fileSocket=null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
this.fileSocket=socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
InputStream is=fileSocket.getInputStream();
String inputLine;
while ((inputLine = in.readLine()) != null) {
if (inputLine.contains("Text") == true)
{
appManager.messageReceived(inputLine);
Log.i("SocketOP","text");}
else if
(inputLine.contains("Text") == false)
{
Log.i("SocketOP","filee");
appManager.fileReceived(is);
}
else{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
fileSocket.shutdownInput();
fileSocket.shutdownOutput();
fileSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
SocketOperator.this.sockets.remove(fileSocket.getInetAddress());
Log.i("SocketOP", "CLOSING CONNECTION");
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
//OutputStreamWriter outputStream = new OutputStreamWriter(socket.getOutputStream());
//outputStream.write("Text");
// outputStream.flush();
String flag = "Text";
message = message+flag;
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
#Override
public boolean sendFile(String ip, int port) {
// TODO Auto-generated method stub
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
Log.i("SocketOP", "sendFILE-1");
File f = new File("/sdcard/chats/gas.jpg/");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
int readData;
byte[] buffer = new byte[1024];
bis.read(buffer, 0,buffer.length);
OutputStream os = socket.getOutputStream();
while((readData=bis.read(buffer))!=-1){
os.write(buffer,0,readData);
Log.i("SocketOP", "sendFILE-3");
}
} catch (IOException e) {
return false;
//e.printStackTrace();
}
// Toast.makeText(this, "Lvbvhhging...", Toast.LENGTH_SHORT).show();
return true;
}
}
This is my IMService service that runs and calls startlistening. i am totally cluless. its giving me an error as suspected. how do i go about resolving this now..
IMService code block :
public void onCreate()
{
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
// showNotification();
conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
// Timer is used to take the friendList info every UPDATE_TIME_PERIOD;
timer = new Timer();
Thread thread = new Thread()
{
#Override
public void run() {
//socketOperator.startListening(LISTENING_PORT_NO);
Random random = new Random();
int tryCount = 0;
while (socketOperator.startListening(10000 + random.nextInt(20000)) == 0 )
{
tryCount++;
if (tryCount > 10)
{
// if it can't listen a port after trying 10 times, give up...
break;
}
}
}
};
thread.start();
}

Try this for fileReceived
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}}
EDIT
You can use 2 sockets, listening on different ports. E.g.
MESSAGE_PORT = 20000
FILE_PORT = 20001
And you run 2 ReceiveConnections, e.g. ReceiveFileConnection and ReceiveMessageConnection. I don't know where do you start port listening, it's not in your code above.
In client you'll also need to split sending to 2 part, message sender sends to MESSAGE_PORT and file sends files to FILE_PORT.
EDIT2
http://pastebin.com/MfMuSF2Q
I split ReceiveConnection into 2 classes ReceiveMessageConnection and ReceiveFileConnection.
I modified method startListening, so it takes parameter which listener we want to start message or file. So you need to call it twice like
startListening(MESSAGE_PORT, true);
startListening(FILE_PORT, false);
But call them in different threads.
To send message you call sendMessage("Message", ip, MESSAGE_PORT) and for files sendFile(ip, FILE_PORT).
Hope this will help.

Related

Send an image through socket: ByteArrayOutputStream.size() return negative value (sometimes )

I am making server-client program, the server is Java on the computer and the client is android app (android studio) and I try to send image from the server to the client, and to show this image on the client's screen by ImageView. The problem is that sometimes its work and sometimes it doesn't work. Looks like there are times that ByteArrayOutputStream.size() return negative value in the client side in the variable len (that keep the length). When the return value is positive it works. Why am I getting negative values (sometimes)?
Server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println("IMAGE");
sendImage(new File("ssss.PNG"));
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client code(android):
public class MainActivity extends AppCompatActivity {
public Socket socket;
public PrintWriter out;
public Scanner in;
public TextView textView;
public DataOutputStream dos=null;
public DataInputStream dis=null;
public ImageView imageView;
public Bitmap bitmap;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.text);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(TAG, "connected1234");
while (in.hasNextLine()) {
String response = in.nextLine();
if (response.startsWith("IMAGE")) {
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
byte[] data;
int len= input.readInt();
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The error:
len: -298696669
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.sendimageexample, PID: 17224
java.lang.NegativeArraySizeException: -298696669
at com.example.sendimageexample.MainActivity$ClientThread.run(MainActivity.java:80)
at java.lang.Thread.run(Thread.java:784)`
I solved it!
client code:
public class MainActivity extends AppCompatActivity {
public Socket socket;
public ImageView imageView;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(TAG, "Adder: "+serverAddr);
socket = new Socket(serverAddr, SERVERPORT);
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
Log.d(TAG, "connected1234");
byte[] data;
int len= input.readInt();//-298696669//17976
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data
.length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
ByteArrayOutputStream bos =new ByteArrayOutputStream();
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.image22);
Log.d(TAG, "bitmap1: "+bitmap1);
bitmap1.compress(Bitmap.CompressFormat.PNG,0,bos);
byte []array=bos.toByteArray();
OutputStream outputStream=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(outputStream);
dos.writeInt(bos.size());
dos.write(array,0,array.length);
Log.d(TAG, "bos.size: "+bos.size());
Log.d(TAG, "bos.array: "+bos.toByteArray());
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
Server jframe=this;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
//this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sendImage(new File("ssss.PNG"));
InputStream inputStream;
try {
inputStream = socket.getInputStream();
DataInputStream dis=new DataInputStream(inputStream);
int size = dis.readInt();
System.out.println("size: "+size);
byte[] imageAr = new byte[size];
dis.readFully(imageAr);
System.out.println("imageAr: "+imageAr);
System.out.println("dis: "+dis);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
jframe.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
revalidate();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
System.out.println("read: "+read);
System.out.println("buf: "+buf);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
System.out.println("ao.toByteArray(): "+ao.toByteArray());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Not able to connect with MySQL after starting Tomcat in Android Eclipse

Code :
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.1.8/android-im/index.php"; //TODO change to your WebAPI Address
private int listeningPort = 0;
private static final String HTTP_REQUEST_FAILED = "failed";
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
//appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}

ConnectionException in android Socket programming

I am working on an android project. Where I am using Socket programming.
But I am getting
java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
from emulator.
I have changed the localhost to
"10.0.2.2" ("http://10.0.2.2/abc.php").
I have also followed the java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused.
But I did not get any solution.
Also please note emulator ip address doesn't match with localhost ip address.So I don't know how to get around this.
Here is the code requested for:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import android.util.Log;
import com.mekya.interfaces.IAppManager;
import com.mekya.interfaces.ISocketOperator;
public class SocketOperator implements ISocketOperator
{
private static final String AUTHENTICATION_SERVER_ADDRESS = "http://billbahadur.com/demo/androidchat/android_im/";
private int listeningPort = 5550;
private static final String HTTP_REQUEST_FAILED = null;
private HashMap<InetAddress, Socket> sockets = new HashMap<InetAddress, Socket>();
private ServerSocket serverSocket = null;
private boolean listening;
private IAppManager appManager;
private class ReceiveConnection extends Thread {
Socket clientSocket = null;
public ReceiveConnection(Socket socket)
{
this.clientSocket = socket;
SocketOperator.this.sockets.put(socket.getInetAddress(), socket);
}
#Override
public void run() {
try {
// PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
if (inputLine.equals("exit") == false)
{
appManager.messageReceived(inputLine);
}
else
{
clientSocket.shutdownInput();
clientSocket.shutdownOutput();
clientSocket.close();
SocketOperator.this.sockets.remove(clientSocket.getInetAddress());
}
}
} catch (IOException e) {
Log.e("ReceiveConnection.run: when receiving connection ","");
}
}
}
public SocketOperator(IAppManager appManager) {
this.appManager = appManager;
}
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
public boolean sendMessage(String message, String ip, int port)
{
try {
String[] str = ip.split("\\.");
byte[] IP = new byte[str.length];
for (int i = 0; i < str.length; i++) {
IP[i] = (byte) Integer.parseInt(str[i]);
}
Socket socket = getSocket(InetAddress.getByAddress(IP), port);
if (socket == null) {
return false;
}
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
} catch (UnknownHostException e) {
return false;
//e.printStackTrace();
} catch (IOException e) {
return false;
//e.printStackTrace();
}
return true;
}
public int startListening(int portNo)
{
listening = true;
try {
serverSocket = new ServerSocket(portNo);
this.listeningPort = portNo;
} catch (IOException e) {
//e.printStackTrace();
this.listeningPort = 0;
return 0;
}
while (listening) {
try {
new ReceiveConnection(serverSocket.accept()).start();
} catch (IOException e) {
//e.printStackTrace();
return 2;
}
}
try {
serverSocket.close();
} catch (IOException e) {
Log.e("Exception server socket", "Exception when closing server socket");
return 3;
}
return 1;
}
public void stopListening()
{
this.listening = false;
}
private Socket getSocket(InetAddress addr, int portNo)
{
Socket socket = null;
if (sockets.containsKey(addr) == true)
{
socket = sockets.get(addr);
// check the status of the socket
if ( socket.isConnected() == false ||
socket.isInputShutdown() == true ||
socket.isOutputShutdown() == true ||
socket.getPort() != portNo
)
{
// if socket is not suitable, then create a new socket
sockets.remove(addr);
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
}
catch (IOException e) {
Log.e("getSocket: when closing and removing", "");
}
}
}
else
{
try {
socket = new Socket(addr, portNo);
sockets.put(addr, socket);
} catch (IOException e) {
Log.e("getSocket: when creating", "");
}
}
return socket;
}
public void exit()
{
for (Iterator<Socket> iterator = sockets.values().iterator(); iterator.hasNext();)
{
Socket socket = (Socket) iterator.next();
try {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
} catch (IOException e)
{
}
}
sockets.clear();
this.stopListening();
appManager = null;
// timer.cancel();
}
public int getListeningPort() {
return this.listeningPort;
}
}
change android_im to android-im because that is what your folder name would be kept in the web server directory of your server. Also mention the port number of the server in the authentication address.

How to increase transport.dump size from 256 bytes to 512 or more bytes in KSOAP2?

I have HttpTransportSE object from KSOAP2 library.
I want to dump response file which may contains mote then simple 9697 character.
currently i am doing it by making transport.
transport.debug = true;
System.out.println("Response ----------"+transport.responseDump);
But it gives me half response with ... at last.
In its internal coding structure i found that it is using 256 bytes for creating and destroying it's responseDump like shown below:
package org.ksoap2.transport;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.List;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.xmlpull.v1.XmlPullParserException;
public class HttpTransportSE extends Transport
{
private ServiceConnection connection;
public HttpTransportSE(String url)
{
super(null, url);
}
public HttpTransportSE(Proxy proxy, String url)
{
super(proxy, url);
}
public HttpTransportSE(String url, int timeout)
{
super(url, timeout);
}
public HttpTransportSE(Proxy proxy, String url, int timeout) {
super(proxy, url, timeout);
}
public void call(String soapAction, SoapEnvelope envelope)
throws IOException, XmlPullParserException
{
call(soapAction, envelope, null);
}
public List call(String soapAction, SoapEnvelope envelope, List headers)
throws IOException, XmlPullParserException
{
if (soapAction == null) {
soapAction = "\"\"";
}
byte[] requestData = createRequestData(envelope);
this.requestDump = (this.debug ? new String(requestData) : null);
this.responseDump = null;
this.connection = getServiceConnection();
this.connection.setRequestProperty("User-Agent", "kSOAP/2.0");
if (envelope.version != 120) {
this.connection.setRequestProperty("SOAPAction", soapAction);
}
this.connection.setRequestProperty("Content-Type", "text/xml");
this.connection.setRequestProperty("Connection", "close");
this.connection.setRequestProperty("Content-Length", "" + requestData.length);
if (headers != null) {
for (int i = 0; i < headers.size(); i++) {
HeaderProperty hp = (HeaderProperty)headers.get(i);
this.connection.setRequestProperty(hp.getKey(), hp.getValue()); } }
this.connection.setRequestMethod("POST");
this.connection.connect();
OutputStream os = this.connection.openOutputStream();
os.write(requestData, 0, requestData.length);
os.flush();
os.close();
requestData = null;
List retHeaders = null;
InputStream is;
try { this.connection.connect();
is = this.connection.openInputStream();
retHeaders = this.connection.getResponseProperties();
} catch (IOException e) {
is = this.connection.getErrorStream();
if (is == null) {
this.connection.disconnect();
throw e;
}
}
if (this.debug) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[256];
while (true)
{
int rd = is.read(buf, 0, 256);
if (rd == -1)
break;
bos.write(buf, 0, rd);
}
bos.flush();
buf = bos.toByteArray();
this.responseDump = new String(buf);
is.close();
is = new ByteArrayInputStream(buf);
}
parseResponse(envelope, is);
return retHeaders;
}
public ServiceConnection getConnection() {
return (ServiceConnectionSE)this.connection;
}
protected ServiceConnection getServiceConnection() throws IOException {
return new ServiceConnectionSE(this.proxy, this.url, this.timeout);
}
public String getHost()
{
String retVal = null;
try
{
retVal = new URL(this.url).getHost();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public int getPort()
{
int retVal = -1;
try
{
retVal = new URL(this.url).getPort();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
public String getPath()
{
String retVal = null;
try
{
retVal = new URL(this.url).getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return retVal;
}
}
You found that its only
int rd = is.read(buf, 0, 256);
So, is there any options to increase responseDump size?
There is no limitation in ksoap, but it is in logcat. Logcat doesn't print long strings, so write in a file or write piece by piece in the log.
if (transport.debug)
{
byte[] is = transport.responseDump.getBytes();
String path="/mnt/sdcard/appData/";
File file = new File(path+"responseDump.xml");
if (!file.exists())
{
file.createNewFile();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); bos.write(is); bos.flush(); bos.close();
}

android socket jelly bean

i want to ask some question for android socket. I create a sample app to send data to wifly module. But when i receive data from module i get socket timeout exception. Without setSoTimeout app freeze to inputStream.read. Here is my code:
package com.socket.wiflysocket;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
protected static final String TAG = "WIflySocket";
EditText textOut;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.isConnected() == false) {
try {
throw new Exception("Network is not connected");
} catch (Exception e) {
e.printStackTrace();
}
}
else {
new SocketThread(textOut.getText().toString()).execute();
textOut.setText("");
}
}};
}
and asynkTask:
package com.socket.wiflysocket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.util.Log;
public class SocketThread extends AsyncTask<String, Void, String>{
private static final String TAG = "SocketAsyncTask";
private static final int BUFFER_SIZE = 8;
private String textViewIn;
private String output;
private Socket socket = null;
private PrintWriter outputStream;
private InputStreamReader inputStream;
public SocketThread(String paramTextViewIn)
{
this.textViewIn = paramTextViewIn;
}
#Override
protected String doInBackground(String ...views) {
Log.d(TAG, "Execute");
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("1.2.3.4", 2000);
socket.setSoTimeout(2000);
outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new InputStreamReader(socket.getInputStream());
if(socket.isConnected()) {
this.sendDataWithString(textViewIn);
output = this.receiveDataFromServer();
}
this.closeSocket();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return output;
}
/*
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
return textViewOut;
}
*/
private void closeSocket() {
if (socket != null) {
if (socket.isConnected()) {
try {
inputStream.close();
outputStream.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendDataWithString(String message) {
if (message != null) {
outputStream.write(message);
outputStream.flush();
}
}
private String receiveDataFromServer() {
String message = "";
try {
int charsRead = 0;
char[] buffer = new char[BUFFER_SIZE];
while ((charsRead = inputStream.read(buffer)) != -1) {
message += new String(buffer).substring(0, charsRead);
}
closeSocket();
return message;
} catch (IOException e) {
//TODO work around
return message;
//return "Error receiving response: " + e.getMessage();
}
}
}
Permission that I add are :
android.permission.INTERNET;
android.permission.ACCESS_NETWORK_STATE
Can you suggest me, what is wrong, and how to fix this issue.
Thanks
Try this -
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
or this -
Reader r = new InputStreamReader(conn.getInputStream());
String line;
StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
sb.append(chars, 0, len);
}
or this one -
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while((k = sock.getInputStream().read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k];
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
resultBuff = tbuff;
}
SocketFactory creates socket for you
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.net.SocketFactory;
...
private Socket socket = null;
public Reader reader = null;
public Writer writer = null;
protected void init(String host, int port) throws ClientException {
try {
socket = SocketFactory.getDefault().createSocket(host, port);
} catch (UnknownHostException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
initDataManagers();
}
protected void initDataManagers() throws ClientException {
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new ClientException(e);
} catch (IOException e) {
throw new ClientException(e);
}
}

Categories

Resources