Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. package a2;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import java.util.*;
  6.  
  7. public class EchoClient {
  8.    
  9.     public static void main(String [] args) {
  10.        
  11. //      if(args.length < 2) {
  12. //          throw new IllegalArgumentException("Argument not specified");
  13. //      }
  14.        
  15.         System.out.println("Attempting to Initialize EchoClient...");
  16.        
  17.         String localhost = "127.0.0.1";//args[0];
  18.         int port = 30000;
  19.        
  20.         try(Socket echoClient = new Socket(localhost, port)) {
  21.             InputStream in = echoClient.getInputStream();
  22.             OutputStream out = echoClient.getOutputStream();
  23.             Scanner input = new Scanner(System.in);
  24.             Boolean status = true;
  25.            
  26.             do {
  27.                 byte [] buffer = input.nextLine().getBytes();
  28.                
  29.                 out.write(buffer);
  30.                
  31.                 int numBytesReceived = 0;
  32.                 int bytesReceived;
  33.                 while(numBytesReceived < buffer.length) {
  34.                     if((bytesReceived = in.read(buffer, numBytesReceived, buffer.length - numBytesReceived)) == -1) {
  35.                         throw new SocketException("Socket Closed");
  36.                     }
  37.                     numBytesReceived += bytesReceived;
  38.                 }
  39.                
  40.                 System.out.println("Echo from Server: " + new String(buffer));
  41.                
  42.                 if(new String(buffer).equalsIgnoreCase(".")) {
  43.                     System.out.println("Exiting Client.");
  44.                     status = false;
  45.                     input.close();
  46.                     echoClient.close();
  47.                 }
  48.             }while(status == true);
  49.            
  50.             input.close();
  51.         }
  52.         catch(Exception e) {
  53.             System.out.println("Unable to Initialize.");
  54.             e.printStackTrace();
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement