You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

84 lines
2.7 KiB

  1. package com.vertsys;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.net.InetAddress;
  7. import java.net.Socket;
  8. import java.net.UnknownHostException;
  9. import java.util.Random;
  10. import static com.vertsys.Server.DEBUG_MODE;
  11. public class Client {
  12. protected static Socket sock;
  13. private static String username;
  14. private static BufferedReader ConsoleIn;
  15. private static final boolean DEBUG_MODE = true;
  16. public static void main(String[] args) {
  17. init();
  18. do {
  19. try {
  20. String msg = ConsoleIn.readLine();
  21. sendMessage(msg);
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. }while (true);
  26. }
  27. public static void init(){
  28. String hostname = null;
  29. try {
  30. hostname = InetAddress.getLocalHost().getHostAddress();
  31. if(DEBUG_MODE)
  32. System.out.println("Host-IP: " + hostname);
  33. } catch (UnknownHostException e) {
  34. e.printStackTrace();
  35. }
  36. int port = 42424;
  37. // Falls die Vergabe eines Benutzernamen fehlschlägt --> "test" + Zufallszahl
  38. Random rand = new Random();
  39. username = "test" + Integer.toString(rand.nextInt());
  40. try {
  41. ConsoleIn = new BufferedReader(new InputStreamReader(System.in));
  42. System.out.print("Your Username: ");
  43. String user = ConsoleIn.readLine();
  44. if (!user.isEmpty())
  45. username = user;
  46. System.out.print("Enter Server hostname: ");
  47. String host = ConsoleIn.readLine();
  48. if(!host.isEmpty())
  49. hostname = host;
  50. System.out.print("Enter port number: ");
  51. String portNum = ConsoleIn.readLine();
  52. if(!portNum.isEmpty())
  53. port = Integer.parseInt(portNum);
  54. }catch (IOException e){
  55. e.printStackTrace();
  56. }
  57. try {
  58. sock = new Socket(hostname, port);
  59. System.out.println("Connection established!");
  60. System.out.println("--------------------------------");
  61. System.out.println("");
  62. new Thread(new ClientThread()).start();
  63. } catch (IOException e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. public static void sendMessage(String message){
  68. String moddedMessage = username + " wrote: " + message + "\n";
  69. try {
  70. DataOutputStream toServer = new DataOutputStream(sock.getOutputStream());
  71. toServer.writeBytes(moddedMessage);
  72. } catch (IOException e) {
  73. e.printStackTrace();
  74. }
  75. }
  76. }