Socket in service on Android writing to server but not reading

461 Views Asked by At

So I created a service in Android that contains a socket which I'm using to send and receive messages from a server. The problem is that the client can send messages to the servers with no problem, but it does not receives messages from the server even though I flushed the server.

Here are the snippets from the code related to the issue:

ServerMulti.java

public class ServerMulti {
ServerSocket srv;
Socket cliente;
static final int PTO=3000;
int cont=0;
Thread t;
Thread1 ha;

public ServerMulti() {
    try{
        srv=new ServerSocket(PTO);
        System.out.println("Server Running on "+srv.getLocalPort());
        atiendeClientes();
    }catch(Exception e){

    }       
}

public void atiendeClientes(){
    try{
        while(true){
            cliente=srv.accept();
            cont+=1;
            ha=new Thread1(cliente,cont);           
            t=new Thread(ha);
            t.start();
        }
    }catch(Exception e){
        e.toString();
    }
}

public static void main(String x[]){
    new ServerMulti();
} 
}

Thread1.java

public class Thread1 implements Runnable{
Socket cliente;
int c;
DataOutputStream dos;
DataInputStream dis;

public Thread1(Socket _cliente,int _c) {
    this.cliente=_cliente;
    this.c=_c;
}

public void run(){
    String cmd="";
    try{
        dos=new DataOutputStream(cliente.getOutputStream());    
        dis=new DataInputStream(cliente.getInputStream());
        do{
cmd=dis.readUTF();
System.out.println("The client "+c+" says: "+cmd);
OutputStream os = client.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if(cmd.equals("Admin 123")){
    bw.write("true");
    System.out.println("I sent true");
}else{
    bw.write("false");
    System.out.println("I got nothing");
}
bw.flush();
}while(!cmd.equals("fin"));
            dis.close();
            dos.close();
            cliente.close();
            System.out.println("Client "+c+" Disconected");

    }catch(Exception e){
        e.toString();
   }
  }
}

SocketService.java

public class SocketService extends Service {
public static final String SERVERIP = "192.168.0.13";
public static final int SERVERPORT = 3000;
DataOutputStream dos;
DataInputStream dis;
String asd = "";
Socket socket;
boolean mRun = false;
String incomingMessage;
InetAddress serverAddr;

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    System.out.println("I am in Ibinder onBind method");
    return myBinder;
}

private final IBinder myBinder = new LocalBinder();
//TCPClient mTcpClient = new TCPClient();

public class LocalBinder extends Binder {
    public SocketService getService() {
        System.out.println("I am in Localbinder ");

        return SocketService.this;

    }
}

@Override
public void onCreate() {
    super.onCreate();
    System.out.println("I am in on create");
}

public void IsBoundable(){
    Toast.makeText(this,"I bind like butter", Toast.LENGTH_LONG).show();
}
public void transm(String msg){
    try{
        dos.writeUTF(msg);
    }catch(Exception e){
        e.toString();
    }
}

public Boolean receive(){
    try{
        String a = dis.readUTF();
        System.out.println(a);
        if (a.equals("true")) {
            return true;
        }else{
            return false;
        }
    }catch (Exception e){
        e.toString();
    }
    return false;
}
@Override
public int onStartCommand(Intent intent,int flags, int startId){
    super.onStartCommand(intent, flags, startId);
    System.out.println("I am in on start");
    //  Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
    Runnable connect = new connectSocket();
    new Thread(connect).start();
    return START_STICKY;
}


class connectSocket implements Runnable {
    @Override
    public void run() {
        mRun=true;
        try {
            //here you must put your computer's IP address.
            Log.e("TCP Client", "C: Connecting...");
            //create a socket to make the connection with the server
            socket = new Socket(SERVERIP, SERVERPORT);
            try {
                //send the message to the server
                dos=new DataOutputStream(socket.getOutputStream());
                dis=new DataInputStream(socket.getInputStream());
                Log.e("TCP Client", "C: Sent.");
                Log.e("TCP Client", "C: Done.");
               /* while (mRun) {
                    incomingMessage = dis.readUTF();



                }*/

               // Log.e("Hi", "Received Message: " + incomingMessage);
            }
            catch (Exception e) {
                Log.e("TCP", "S: Error", e);
            }
        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
        }

    }

}


@Override
public void onDestroy() {
    super.onDestroy();
    try {
        socket.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    socket = null;
}
}

And this is what I use on the android activity Login.java

public class Login extends Activity {
EditText ed1, ed2;
MCom mcom;
boolean mIsBound;
SocketService mBoundService;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    setGui(null);
    startService(new Intent(Login.this, SocketService.class));
    doBindService();
}

private ServiceConnection mConnection = new ServiceConnection() {
    //EDITED PART
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        // TODO Auto-generated method stub
        mBoundService = ((SocketService.LocalBinder)service).getService();

    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // TODO Auto-generated method stub
        mBoundService = null;
    }

};


private void doBindService() {
    bindService(new Intent(Login.this, SocketService.class), mConnection,     Context.BIND_AUTO_CREATE);
    mIsBound = true;
    if(mBoundService!=null){
        mBoundService.IsBoundable();
    }
}

private void doUnbindService() {
    if (mIsBound) {
        // Detach our existing connection.
        unbindService(mConnection);
        mIsBound = false;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    doUnbindService();
}

public void  setGui(View v){
    ed1=(EditText)findViewById(R.id.editText);
    ed2=(EditText)findViewById(R.id.editText2);
}

public void Ing (View v){
mBoundService.transm(ed1.getText().toString()+" "+ed2.getText().toString());

    if(mBoundService.receive()==true){
        mostSald();
        Toast.makeText(this, "Welcome!", Toast.LENGTH_SHORT).show();
    }else{
        Toast.makeText(this, "Not Valid Credentials", Toast.LENGTH_SHORT).show();
    }
   }

public void exit (View v){
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
}

public void showBalance(){
    Intent i= new Intent(this, Balance.class);
    startActivity(i);
}
}

It always goes to the last else since it appears that is not receiving anything from the server plus the variable "a" in the method receive it always stays empty, but in the server console I get the "I sent true" message.

Any ideas? Thanks in advance :)

0

There are 0 best solutions below