daily pastebin goal
62%
SHARE
TWEET

Untitled

a guest Feb 13th, 2018 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class TcpClient {
  2.  
  3.     public static final String SERVER_IP = "192.168.1.8"; //server IP address
  4.     public static final int SERVER_PORT = 1234;
  5.     // message to send to the server
  6.     private String mServerMessage;
  7.     // sends message received notifications
  8.     private OnMessageReceived mMessageListener = null;
  9.     // while this is true, the server will continue running
  10.     private boolean mRun = false;
  11.     // used to send messages
  12.     private PrintWriter mBufferOut;
  13.     // used to read messages from the server
  14.     private BufferedReader mBufferIn;
  15.  
  16.     /**
  17.      * Constructor of the class. OnMessagedReceived listens for the messages received from server
  18.      */
  19.     public TcpClient(OnMessageReceived listener) {
  20.         mMessageListener = listener;
  21.     }
  22.  
  23.     /**
  24.      * Sends the message entered by client to the server
  25.      *
  26.      * @param message text entered by client
  27.      */
  28.     public void sendMessage(final String message) {
  29.         Runnable runnable = new Runnable() {
  30.             @Override
  31.             public void run() {
  32.                 if (mBufferOut != null) {
  33.                     Log.d(TAG, "Sending: " + message);
  34.                     mBufferOut.println(message + "rn");
  35.                     mBufferOut.flush();
  36.                 }
  37.             }
  38.         };
  39.     Thread thread = new Thread(runnable);
  40.     thread.start();
  41. }
  42.  
  43.     /**
  44.      * Close the connection and release the members
  45.      */
  46.     public void stopClient() {
  47.  
  48.         mRun = false;
  49.  
  50.         if (mBufferOut != null) {
  51.             mBufferOut.flush();
  52.             mBufferOut.close();
  53.         }
  54.  
  55.         mMessageListener = null;
  56.         mBufferIn = null;
  57.         mBufferOut = null;
  58.         mServerMessage = null;
  59.     }
  60.  
  61.     public void run() {
  62.  
  63.         mRun = true;
  64.  
  65.         try {
  66.             //here you must put your computer's IP address.
  67.             InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
  68.  
  69.             Log.e("TCP Client", "C: Connecting...");
  70.  
  71.             //create a socket to make the connection with the server
  72.             Socket socket = new Socket(serverAddr, SERVER_PORT);
  73.  
  74.             try {
  75.  
  76.                 //sends the message to the server
  77.                 mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
  78.  
  79.                 //receives the message which the server sends back
  80.                 mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  81.  
  82.  
  83.                 //in this while the client listens for the messages sent by the server
  84.                 while (mRun) {
  85.  
  86.                     mServerMessage = mBufferIn.readLine();
  87.  
  88.                     if (mServerMessage != null && mMessageListener != null) {
  89.                         //call the method messageReceived from MyActivity class
  90.                         mMessageListener.messageReceived(mServerMessage);
  91.                     }
  92.  
  93.                 }
  94.  
  95.                 Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
  96.  
  97.             } catch (Exception e) {
  98.  
  99.                 Log.e("TCP", "S: Error", e);
  100.  
  101.             } finally {
  102.                 //the socket must be closed. It is not possible to reconnect to this socket
  103.                 // after it is closed, which means a new socket instance has to be created.
  104.                 socket.close();
  105.             }
  106.  
  107.         } catch (Exception e) {
  108.  
  109.             Log.e("TCP", "C: Error", e);
  110.  
  111.         }
  112.  
  113.     }
  114.  
  115.     //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
  116.     //class at on asynckTask doInBackground
  117.     public interface OnMessageReceived {
  118.         public void messageReceived(String message);
  119.     }
  120.  
  121. }
  122.    
  123. public class MainActivity extends Activity {
  124.  
  125.     TcpClient mTcpClient;
  126.  
  127.     //............
  128.    
  129. public class ConnectTask extends AsyncTask<String, String, TcpClient> {
  130.  
  131.     @Override
  132.     protected TcpClient doInBackground(String... message) {
  133.  
  134.         //we create a TCPClient object
  135.         mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
  136.             @Override
  137.             //here the messageReceived method is implemented
  138.             public void messageReceived(String message) {
  139.                 //this method calls the onProgressUpdate
  140.                 publishProgress(message);
  141.             }
  142.         });
  143.         mTcpClient.run();
  144.  
  145.         return null;
  146.     }
  147.  
  148.     @Override
  149.     protected void onProgressUpdate(String... values) {
  150.         super.onProgressUpdate(values);
  151.         //response received from server
  152.         Log.d("test", "response " + values[0]);
  153.         //process server response here....
  154.  
  155. }
  156.    
  157. new ConnectTask().execute("");
  158.    
  159. //sends the message to the server
  160. if (mTcpClient != null) {
  161.     mTcpClient.sendMessage("testing");
  162. }
  163.    
  164. if (mTcpClient != null) {
  165.     mTcpClient.stopClient();
  166. }
  167.    
  168. mRun = true;
  169.  
  170. try {
  171.     InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
  172.     Log.e("TCP Client", "C: Connecting...");
  173.     Socket socket = new Socket(serverAddr, SERVER_PORT);
  174.     try {
  175.         mBufferOut = new PrintWriter(socket.getOutputStream());
  176.         Log.e("TCP Client", "C: Sent.");
  177.         mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  178.         int charsRead = 0; char[] buffer = new char[1024]; //choose your buffer size if you need other than 1024
  179.  
  180.         while (mRun) {
  181.             charsRead = mBufferIn.read(buffer);
  182.             mServerMessage = new String(buffer).substring(0, charsRead);
  183.             if (mServerMessage != null && mMessageListener != null) {
  184.                 mMessageListener.messageReceived(mServerMessage);}
  185.             mServerMessage = null;
  186.         }
  187.         Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");
  188.    
  189. @Override
  190. protected void onProgressUpdate(String... values) {
  191.         super.onProgressUpdate(values);
  192.         Log.d("test", "response " + values[0]);
  193.         response.setText(response.getText() + "/n" +values[0]);
  194. }
  195.    
  196. public class MainActivity extends AppCompatActivity {
  197. TextView response; //...so on
RAW Paste Data
Top