1. Download our Official Android App: Forums for Android!

Apps Android Socket Client

Discussion in 'Android Development' started by Andre Correia, Jun 3, 2016.

  1. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Hi,

    I'm doing a desktop server application in java with android clients. I'm using sockets to provide the communication.

    I have create an instance of tcpClient on MainActivity and I would like to know how could I call the method 'sendMessage' on other activities.

    Should I create an instance of tcpClient on all activities?

    Thanks

    Server class
    Code (Text):
    1.  
    2. import java.net.*;
    3. import java.io.*;
    4.  
    5. public class Server {
    6.  
    7.     public static void main(String[] args) throws IOException{
    8.  
    9.         boolean listening = true;
    10.  
    11.         try (ServerSocket serverSocket = new ServerSocket(4444)){
    12.  
    13.             while(listening){
    14.                 new ServerThread(serverSocket.accept()).start();
    15.             }
    16.         } catch (IOException e) {
    17.             System.out.println("Could not listen on port: 4444");
    18.             System.exit(-1);
    19.         }
    20.  
    21.     }
    22. }
    23.  

    ServerThread
    Code (Text):
    1.  
    2. import java.net.*;
    3. import java.io.*;
    4.  
    5. public class ServerThread extends Thread {
    6.    
    7.     private Socket socket = null;
    8.  
    9.     public ServerThread(Socket socket) {
    10.         super("ServerThread");
    11.         this.socket = socket;
    12.     }
    13.    
    14.     public void run() {
    15.  
    16.         try (
    17.             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
    18.             BufferedReader in = new BufferedReader(
    19.                 new InputStreamReader(
    20.                     socket.getInputStream()));
    21.         ) {
    22.             String inputLine, outputLine;
    23.             GameProtocol gp = new GameProtocol();
    24.             outputLine = gp.processInput(null);
    25.             //System.out.println(outputLine);
    26.             //out.println(outputLine);
    27.  
    28.             while ((inputLine = in.readLine()) != null) {
    29.                 //System.out.println(outputLine);
    30.                 outputLine = gp.processInput(inputLine);
    31.                 System.out.println(outputLine);
    32.                 out.println(outputLine);
    33.                 if (outputLine.equals("Bye"))
    34.                     break;
    35.             }
    36.             socket.close();
    37.         } catch (IOException e) {
    38.             e.printStackTrace();
    39.         }
    40.     }
    41. }
    42. ]
    TcpClient class
    Code (Text):
    1.  
    2. import android.util.Log;
    3.  
    4. import java.io.*;
    5. import java.net.*;
    6.  
    7. /**
    8.  * Created by andrecorreia on 03/06/16.
    9.  */
    10. public class TcpClient {
    11.  
    12.     public static final String SERVER_IP = "10.0.2.2"; // computer IP address
    13.     public static final int SERVER_PORT = 4444;
    14.  
    15.     // message to send to the server
    16.     private String mServerMessage;
    17.     // sends message received notifications
    18.     private OnMessageReceived mMessageListener = null;
    19.     // while this is true, the server will continue running
    20.     private boolean mRun = false;
    21.     // used to send messages
    22.     private PrintWriter mBufferOut;
    23.     // used to read messages from the server
    24.     private BufferedReader mBufferIn;
    25.  
    26.     /**
    27.      * Constructor of the class. OnMessagedReceived listens for the messages received from server
    28.      */
    29.     public TcpClient(OnMessageReceived listener) {
    30.         mMessageListener = listener;
    31.     }
    32.  
    33.     /**
    34.      * Sends the message entered by client to the server
    35.      *
    36.      * @param message text entered by client
    37.      */
    38.     public void sendMessage(String message) {
    39.         if (mBufferOut != null && !mBufferOut.checkError()) {
    40.             mBufferOut.println(message);
    41.             mBufferOut.flush();
    42.         }
    43.     }
    44.  
    45.     /**
    46.      * Close the connection and release the members
    47.      */
    48.     public void stopClient() {
    49.         Log.i("Debug", "stopClient");
    50.  
    51.         // send mesage that we are closing the connection
    52.         //sendMessage(Constants.CLOSED_CONNECTION + "Kazy");
    53.  
    54.         mRun = false;
    55.  
    56.         if (mBufferOut != null) {
    57.             mBufferOut.flush();
    58.             mBufferOut.close();
    59.         }
    60.  
    61.         mMessageListener = null;
    62.         mBufferIn = null;
    63.         mBufferOut = null;
    64.         mServerMessage = null;
    65.     }
    66.  
    67.     public void run() {
    68.  
    69.         mRun = true;
    70.  
    71.         try {
    72.             //here you must put your computer's IP address.
    73.             InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
    74.  
    75.             //InetAddress serverAddr = InetAddress.getLocalHost();
    76.             Log.e("TCP Client", "C: Connecting...");
    77.  
    78.             //create a socket to make the connection with the server
    79.             Socket socket = new Socket("192.168.1.92", SERVER_PORT);
    80.  
    81.             try {
    82.                 Log.i("Debug", "inside try catch");
    83.                 //sends the message to the server
    84.                 mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
    85.  
    86.                 //receives the message which the server sends back
    87.                 mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    88.                 // send login name
    89.                 //sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());
    90.                 //sendMessage("Hi");
    91.                 //in this while the client listens for the messages sent by the server
    92.                 while (mRun) {
    93.                     mServerMessage = mBufferIn.readLine();
    94.                     if (mServerMessage != null && mMessageListener != null) {
    95.                         //call the method messageReceived from MyActivity class
    96.                         mMessageListener.messageReceived(mServerMessage);
    97.                     }
    98.  
    99.                 }
    100.                 Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
    101.  
    102.             } catch (Exception e) {
    103.  
    104.                 Log.e("TCP", "S: Error", e);
    105.  
    106.             } finally {
    107.                 //the socket must be closed. It is not possible to reconnect to this socket
    108.                 // after it is closed, which means a new socket instance has to be created.
    109.                 socket.close();
    110.             }
    111.  
    112.         } catch (Exception e) {
    113.  
    114.             Log.e("TCP", "C: Error", e);
    115.  
    116.         }
    117.  
    118.     }
    119.  
    120.     //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    121.     //class at on asynckTask doInBackground
    122.     public interface OnMessageReceived {
    123.         public void messageReceived(String message);
    124.     }
    125. }
    126.  
    127.  
    Main Activity
    Code (Text):
    1.  
    2. import android.app.Activity;
    3. import android.content.Intent;
    4. import android.os.AsyncTask;
    5. import android.os.Bundle;
    6. import android.view.Menu;
    7. import android.view.MenuItem;
    8. import android.view.View;
    9. import android.view.View.OnClickListener;
    10.  
    11.  
    12. public class MainActivity extends Activity implements OnClickListener {
    13.  
    14.     public static TcpClient tcpClient;
    15.  
    16.     @Override
    17.     protected void onCreate(Bundle savedInstanceState) {
    18.         super.onCreate(savedInstanceState);
    19.         setContentView(R.layout.activity_main);
    20.  
    21.         new ConnectTask().execute("");
    22.  
    23.         // Set up click listeners for all the buttons
    24.         View playNowButton = findViewById(R.id.playNow_button);
    25.         playNowButton.setOnClickListener(this);
    26.  
    27.         View optionsButton = findViewById(R.id.options_button);
    28.         optionsButton.setOnClickListener(this);
    29.  
    30.         View helpButton = findViewById(R.id.help_button);
    31.         helpButton.setOnClickListener(this);
    32.  
    33.         View exitButton = findViewById(R.id.exit_button);
    34.         exitButton.setOnClickListener(this);
    35.         //---------------------------------------------
    36.     }
    37.  
    38.  
    39.     @Override
    40.     public void onClick(View v) {
    41.         Intent i;
    42.         switch (v.getId()){
    43.             case R.id.playNow_button:
    44.                 i = new Intent(this, PlayNowActivity.class);
    45.                 startActivity(i);
    46.                 break;
    47.             case R.id.options_button:
    48.                 i = new Intent(this, OptionsActivity.class);
    49.                 tcpClient.sendMessage("options");
    50.                 startActivity(i);
    51.                 break;
    52.             case R.id.help_button:
    53.                 i = new Intent(this, HelpActivity.class);
    54.                 tcpClient.sendMessage("help");
    55.                 startActivity(i);
    56.                 break;
    57.             case R.id.exit_button:
    58.                 finish();
    59.                 break;
    60.         }
    61.     }
    62.  
    63.     public class ConnectTask extends AsyncTask<String,String,TcpClient> {
    64.  
    65.         @Override
    66.         protected TcpClient doInBackground(String... message) {
    67.  
    68.             //we create a TCPClient object and
    69.             tcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
    70.                 @Override
    71.                 //here the messageReceived method is implemented
    72.                 public void messageReceived(String message) {
    73.  
    74.                     //this method calls the onProgressUpdate
    75.                     publishProgress(message);
    76.  
    77.                 }
    78.             });
    79.             tcpClient.run();
    80.  
    81.             return null;
    82.         }
    83.  
    84.         @Override
    85.         protected void onProgressUpdate(String... values) {
    86.             super.onProgressUpdate(values);
    87.         /*View view = adapter.getChildView(0, 0, false, null, null);
    88.         TextView text = (TextView) view.findViewById(R.id.betChildOdd);
    89.         child2.get(0).get(0).put("OLD", text.getText().toString());
    90.         child2.get(0).get(0).put(CONVERTED_ODDS, values[0].toString());
    91.         child2.get(0).get(0).put("CHANGE", "TRUE");
    92.         adapter.notifyDataSetChanged();*/
    93.         }
    94.     }
    95.  
    96.     @Override
    97.     public boolean onCreateOptionsMenu(Menu menu) {
    98.         // Inflate the menu; this adds items to the action bar if it is present.
    99.         getMenuInflater().inflate(R.menu.menu_main, menu);
    100.         return true;
    101.     }
    102.  
    103.     @Override
    104.     public boolean onOptionsItemSelected(MenuItem item) {
    105.         // Handle action bar item clicks here. The action bar will
    106.         // automatically handle clicks on the Home/Up button, so long
    107.         // as you specify a parent activity in AndroidManifest.xml.
    108.         int id = item.getItemId();
    109.  
    110.         //noinspection SimplifiableIfStatement
    111.         if (id == R.id.action_settings) {
    112.             return true;
    113.         }
    114.  
    115.         return super.onOptionsItemSelected(item);
    116.     }
    117.  
    118. }
    119.  
    Options Activity
    Code (Text):
    1.  
    2. import android.app.Activity;
    3. import android.content.Intent;
    4. import android.content.SharedPreferences;
    5. import android.os.Bundle;
    6. import android.view.View;
    7. import android.view.View.OnClickListener;
    8. import android.widget.Button;
    9. import android.widget.EditText;
    10. import android.widget.TextView;
    11.  
    12. import java.io.PrintWriter;
    13. import java.net.Socket;
    14.  
    15. public class OptionsActivity extends Activity implements OnClickListener{
    16.  
    17.     private PrintWriter printwriter;
    18.     private EditText textField;
    19.     private String message;
    20.     private String pieceSelected;
    21.  
    22.     TextView response;
    23.  
    24.     @Override
    25.     protected void onCreate(Bundle savedInstanceState) {
    26.         super.onCreate(savedInstanceState);
    27.         setContentView(R.layout.activity_options);
    28.  
    29.         textField = (EditText) findViewById(R.id.name_editText);
    30.  
    31.         // Set up click listeners for all the buttons
    32.         View saveButton = findViewById(R.id.saveOptions_button);
    33.         //saveButton.setOnClickListener(this);
    34.  
    35.         View backOptionsButton = findViewById(R.id.backOptions_button);
    36.         backOptionsButton.setOnClickListener(this);
    37.  
    38.         View choosePieceButton = findViewById(R.id.choosePiece_button);
    39.         choosePieceButton.setOnClickListener(this);
    40.  
    41.         saveButton.setOnClickListener(new OnClickListener() {
    42.  
    43.             @Override
    44.             public void onClick(View arg0) {
    45.                 message = textField.getText().toString(); // get the text message on the text field
    46.  
    47.                 message+=";";
    48.                 message+=pieceSelected;
    49.  
    50.                 MainActivity.tcpClient.sendMessage(message);
    51.             }
    52.         });
    53.     }
    54.  
    55.     //@Override
    56.     public void onClick(View v) {
    57.         if (v.getId() == R.id.backOptions_button) {
    58.             finish();
    59.         } else if (v.getId() == R.id.saveOptions_button) {
    60.  
    61.         } else if (v.getId() == R.id.choosePiece_button) {
    62.             Intent i = new Intent(this, GridViewPiecesActivity.class);
    63.             startActivityForResult(i,1);
    64.         }
    65.  
    66.     }
    67.  
    68.     public void onActivityResult(int requestCode, int resultCode, Intent data) {
    69.         super.onActivityResult(requestCode, resultCode, data);
    70.         if (requestCode == 1) {
    71.             if(resultCode == RESULT_OK){
    72.                 pieceSelected=data.getStringExtra("edittextvalue");
    73.             }
    74.         }
    75.     }
    76.  
    77. }
    78.  
     

    Advertisement

  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
  3. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Thanks for helping me. Your answer was very helpful.

    I need your help again.

    Could anyone tell me how can I get access on server message response at MainActivity?

    Thanks
     
  4. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    No one could help me please?

    Thanks
     
  5. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
    Your question is not clear
     
  6. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Hi,

    Imagine somewhere in ManyActivity I send a message to server.

    Code (Text):
    1. tcpClient.sendMessage("something");
    Then, how could I get the server response in that Activity?

    Thanks
     
  7. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
    Your TcpClient class has a constructor which takes a listener parameter. The method messageReceived() is called on the listener whenever a message is received by the TcpClient.

    Why not create an instance of the TcpClient, and pass in a listener?
     
  8. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Thanks for helping me.

    Imagine I'm at MainActivity and that activity has a button. Then I want to jump to another activty onClick event of that button, based on server response.

    Something like that: if server response is "yes" I start a new activty, otherwise no.

    Code (Text):
    1. @Override
    2. public void onClick(View v) {
    3.     Intent i;
    4.     switch (v.getId()) {
    5.         case R.id.playNow_button:
    6.             tcpClient.sendMessage("")
    7.             if (response.equalsIgnoreCase("yes")) {
    8.                 i = new Intent(this, SettingsActivity.class);
    9.                 startActivity(i);
    10.                 break;
    11.             }
    Thanks
     
  9. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
    So the messageReceived() method of your OnMessageReceived() method would be the place to put this code

    Code (Text):
    1.  
    2. if (response.equalsIgnoreCase("yes")) {
    3.                 i = new Intent(this, SettingsActivity.class);
    4.                 startActivity(i);
    5.             }
    6.  
     
  10. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Ok.

    Thanks a lot! Your help was very useful!
     
  11. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    Hi again,

    I need your help again, please.

    As you can see above I made a server that support many clients, each one with a thread.

    Until now clients are sending messages to the server and then do something based on server response.

    But now I need that server send a message to a specific client and I don't know how.

    Could you help me please?

    Thanks
     
  12. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
    But isn't there a one to one connection between client and server?

    You create a new TcpClient object to communicate with the server. When the server detects an incoming client request, then a new thread will be created to handle it.

    You call ServerSocket.accept(), which just blocks until an incoming connection request is detected.
     
    #12 LV426, Jun 6, 2016
    Last edited: Jun 6, 2016
  13. Andre Correia

    Andre Correia Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    8
    Joined:
    Jun 3, 2016

    Jun 3, 2016
    8
    0
    5
    Male
    But what changes have I have to do in order to server could send a message to a specific client without a request from him?

    Thanks
     
  14. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,873
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,873
    11,508
    1,988
    Male
    Software developer
    South West of England
    Well the client must initiate the connection, not the other way round.

    Once the server has received an initial message from the client, you could then possibly hold the connection open to push messages to the client from the server.
     

Share This Page

Loading...