Advertisement
Guest User

Untitled

a guest
Nov 14th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. package cd2020create;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.*;
  6. import java.io.PrintWriter;
  7. import java.net.*;
  8. import java.net.Socket;
  9. import java.util.Date;
  10. import java.util.Scanner;
  11.  
  12. public class SocketClient {
  13. public static void main(String args[]) throws IOException, NumberFormatException, InterruptedException, NullPointerException {
  14. String portnos = "0000";
  15. Scanner sc = new Scanner(System.in);
  16. InetAddress ip = InetAddress.getByName("10.12.97.118");
  17. System.out.println("Please enter a port to connect to (max 5 digits).");
  18. do {
  19. portnos = sc.next();
  20. try {
  21. Integer.parseInt(portnos);
  22. } catch (Exception e) {
  23. portnos = "100000000";
  24. }
  25. if (Integer.parseInt(portnos) > 99999) {
  26. System.err.println("Invalid port");
  27. portnos = "100000000";
  28. }
  29. } while (Integer.parseInt(portnos) > 99999);
  30. Socket sklocal = null;
  31. Date date = new Date();
  32. long timeMilli = date.getTime();
  33. System.out.print("Connecting...");
  34. long timeMilli2 = date.getTime();
  35. while (true) {
  36. if (timeMilli2 - timeMilli > 10000)
  37. {
  38. System.err.println("Error: Connection Timeout");
  39. }
  40. try {
  41. sklocal = new Socket(ip, Integer.parseInt(portnos));
  42. if (sklocal.getRemoteSocketAddress() != null) {
  43. break;
  44. }
  45. } catch (Exception e) {
  46. timeMilli2 = date.getTime();
  47. System.out.print(".");
  48. }
  49. }
  50. System.out.println("Connected to " + sklocal.getRemoteSocketAddress());
  51. OutputStream out = sklocal.getOutputStream();
  52. DataOutputStream dataOut = new DataOutputStream(out);
  53. InputStream in = new DataInputStream(sklocal.getInputStream());
  54. DataInputStream dataIn = new DataInputStream(in);
  55. while (true) {
  56. try {
  57. sklocal.getOutputStream();
  58. String input = sc.next();
  59. dataOut.writeUTF(input);
  60. System.out.println(dataIn.readUTF());
  61. } catch (Exception NullPointerException) { }
  62. }
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement