Advertisement
chaminga

client

Apr 15th, 2014
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.Console;
  4. import java.io.DataInputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.OutputStream;
  12. import java.net.Socket;
  13. import java.net.SocketException;
  14. import java.util.Scanner;
  15.  
  16. public class FileClient {
  17. public static void main(String[] args) throws Exception {
  18.  
  19. // Give error if no server ip and port passed as arguments
  20. if (args.length != 2) {
  21. System.err.println("Usage: java FileClient <server address> <port number>");
  22. System.exit(1);
  23. }
  24.  
  25. String serverName = args[0];
  26. int serverPort = Integer.parseInt(args[1]);
  27.  
  28. try {
  29. System.out.println("Connecting to " + serverName + " on port " + serverPort);
  30. Socket client = new Socket(serverName, serverPort);
  31. System.out.println("Just connected to " + client.getRemoteSocketAddress() + "\n");
  32.  
  33. Scanner scanner = new Scanner(System.in);
  34. System.out.println("Enter a command: ");
  35. String command = scanner.nextLine();
  36. scanner.close();
  37.  
  38. OutputStream outToServer = client.getOutputStream();
  39. DataOutputStream out = new DataOutputStream(outToServer);
  40. out.writeUTF(command);
  41.  
  42. //out.writeUTF("Hello from " + client.getLocalSocketAddress());
  43. InputStream inFromServer = client.getInputStream();
  44. DataInputStream in = new DataInputStream(inFromServer);
  45.  
  46. String value;
  47. while (in.available() > 0 && (value = in.readUTF()) != null) {
  48. System.out.println(value);
  49. }
  50. in.close();
  51. out.close();
  52. client.close();
  53. } catch (SocketException e){
  54. System.out.println("Error connecting to the server");
  55. }
  56.  
  57. catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement