Search code examples
androidmain-activity

How to get message to send from server to Android


I have made a program to send a message from a client to a server(2 android devices), but the message is not being sent.

Here is the code of the client side application:

package com.example.clientphone;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.*;



public class MainActivity extends ActionBarActivity {

    private EditText ipaddress , textfield;
    private Button send;
    private String ip , message;
    private Socket client;
    private PrintWriter printwriter;



   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       ipaddress = (EditText)findViewById(R.id.editText1);
       textfield = (EditText)findViewById(R.id.editText2);
       send = (Button) findViewById(R.id.button1);
       StrictMode.ThreadPolicy policy = new      StrictMode.ThreadPolicy.Builder().permitAll().build();// enabling strict mode and setting thread policy
    StrictMode.setThreadPolicy(policy);
    send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            message = textfield.getText().toString();
            ip = ipaddress.getText().toString();// getting ip address
            textfield.setText(" ");
            try {

                client = new Socket(ip, 5200);// ip address is entered over here....
                printwriter = new PrintWriter(client.getOutputStream() , true);// getting the outputstream
                printwriter.write(message);// writing the message
                printwriter.flush();// flushing the printwriter
                printwriter.close();// closing printwriter
                client.close();// closing client




            } catch (UnknownHostException e) {
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();    
            }

        }
    });
}



}

Here is the code for server side application. I have chosen the port 5200 to connect on. I want the user to enter the IP address of the other device and not keep it hard-coded:

package com.example.serverphone;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;


public class MainActivity extends ActionBarActivity {

TextView message;
private ServerSocket socket;
private Handler UpdateConversationHandler;
Thread ServerThread = null;
public static final int port = 5200;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    message = (TextView)findViewById(R.id.textView1);
    UpdateConversationHandler = new Handler();
    this.ServerThread = new Thread(new ServerThread());
    this.ServerThread.start();
}

@Override
protected void onStop() {
    super.onStop();
    try {

        socket.close();


    } catch (IOException e) {
        e.printStackTrace();
    }
}


class ServerThread implements Runnable{

@Override
public void run() {
    Socket socket2 = null;

    try {

        socket = new ServerSocket(port);




    } catch (IOException e) {
        e.printStackTrace();
    }
    while(!Thread.currentThread().isInterrupted()){
        try {
            socket2 = socket.accept();
            BufferedReaderThread commThread = new BufferedReaderThread(socket2);
            new Thread(commThread).start();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

}

   }

   class BufferedReaderThread implements Runnable{

   private Socket clientSocket;
   private BufferedReader input;

   public BufferedReaderThread(Socket clientSocket) {
       this.clientSocket = clientSocket;

       try {


           this.input = new BufferedReader(new  InputStreamReader(this.clientSocket.getInputStream()));




    } catch (IOException e) {
        e.printStackTrace();
    }
}









@Override
public void run() {
    while(!Thread.currentThread().isInterrupted()){// making sure the thread is not interrupted...
        try {

            String read = input.readLine();
                if(read != null){

                    UpdateConversationHandler.post(new updateUIConversation(read));
                }




        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}


 }

   class updateUIConversation implements Runnable{

   private String msg;
   public updateUIConversation(String str){
       this.msg = str;
   }

@Override
public void run() {
    message.setText(message.getText().toString() + msg + "/n");

}


}  
}

Solution

  • In your client you are doing network operation on the main thread. Do them in a separate thread. Do not silently supress exceptions and you will see in the log.

    new Thread(new Runnable() {
    public void run() {
    try {
      Socket client = new Socket(ip, 5200);
      PrintWriter = new PrintWriter(client.getOutputStream() , true);
      printwriter.write(message);// writing the message
      printwriter.flush();// flushing the printwriter
      printwriter.close();// closing printwriter
      client.close();// closing client
    } catch (Exception x) { Log.e("CLIENT", "Exception " + x); }
    }).start();