Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 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.98.56");
  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. System.out.print("Please enter a username (Must not contain spaces): ");
  52. String username = sc.next();
  53. System.out.println();
  54. DataOutputStream dataOut = new DataOutputStream(sklocal.getOutputStream());
  55. DataInputStream dataIn = new DataInputStream(sklocal.getInputStream());
  56. boolean useless = false;
  57. String tempb = "";
  58. int x = 0;
  59. while (true) {
  60. if (x > 0) {
  61. System.out.print("[" + username + "]" + ": ");
  62. }
  63. String input = "[" + username + "]" + ": " + sc.nextLine();
  64. useless = true;
  65. dataOut.writeUTF(input);
  66. if (dataOut.equals(null))
  67. tempb = dataIn.readUTF();
  68. System.out.print(tempb);
  69. if (!(tempb.equals("")))
  70. {
  71. System.out.println();
  72. }
  73. x++;
  74. }
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement