ConnectionException in android Socket programming - android

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.

Related

Unable to read data (send by server) at Client Side

I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} /*finally {
if (socket != null) {
try {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.

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;
}
}

OBD2 - ELM327 WIFI adapter

I am developing andorid aplication for connection to ELM327 for car unit trought Wifi (my adapter: http://www.obdinnovations.com/mini-vgate-elm327-wifi-obd2-auto-diagnostics-scanner).
How should I connect to this OBD2 adapter and then send some signals?
OutputStream outStream = null;
InputStream inStream = null;
Socket socket = null;
InetAddress serverAddr = null;
String serverProtocol = "http";
String serverIpAddress = "192.168.0.10";
public static final int SERVERPORT = 35000;
try {
serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, SERVERPORT);
socket.setKeepAlive(true);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sendDataToOBD(socket1, "ATZ\r");
Log.e("OBD: ATZ", readDataFromOBD(socket));
public void sendDataToOBD(Socket socket1, String paramString) {
try {
outStream = socket1.getOutputStream();
byte[] arrayOfBytes = paramString.getBytes();
outStream.write(arrayOfBytes);
} catch (Exception localIOException1) {
localIOException1.printStackTrace();
}
}
public String readDataFromOBD(Socket socket1) {
while (true) {
try {
inStream = socket1.getInputStream();
String str1 = "";
char c = (char) inStream.read();
str1 = str1 + c;
if (c == '>') {
String datafromOBD = str1.substring(0, -2 + str1.length()).replaceAll(" ", "").trim();
return datafromOBD;
}
} catch (IOException localIOException) {
return localIOException.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I try also with:
URL url = null;
try {
url = new URL(serverProtocol, serverIpAddress, SERVERPORT, "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.connect();
} catch (IOException e) {
e.printStackTrace();
}
And methods param was HttpURLConnection connection instead of Socket socket1.
But I can't receive any signal. What's wrong with my code? Any suggestions?

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);
}
}

android: file transfer through sockets

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.

Categories

Resources