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.

68 lines
2.1 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.Socket;
  7. import java.util.Random;
  8. public class Client {
  9. protected static Socket sock;
  10. private static String username;
  11. private static BufferedReader ConsoleIn;
  12. public static void main(String[] args) {
  13. init();
  14. do {
  15. try {
  16. String msg = ConsoleIn.readLine();
  17. sendMessage(msg);
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. }while (true);
  22. }
  23. public static void init(){
  24. String hostname = "localhost";
  25. int port = 42424;
  26. // Falls die Vergabe eines Benutzernamen fehlschlägt --> "test" + Zufallszahl
  27. Random rand = new Random();
  28. username = "test" + Integer.toString(rand.nextInt(4));
  29. try {
  30. ConsoleIn = new BufferedReader(new InputStreamReader(System.in));
  31. System.out.print("Your Username: ");
  32. String user = ConsoleIn.readLine();
  33. if (user != "")
  34. username = user;
  35. System.out.print("Enter Server hostname: ");
  36. hostname = ConsoleIn.readLine();
  37. System.out.print("Enter port number: ");
  38. port = Integer.parseInt(ConsoleIn.readLine());
  39. }catch (IOException e){
  40. e.printStackTrace();
  41. }
  42. try {
  43. sock = new Socket(hostname, port);
  44. System.out.println("Connection established!");
  45. System.out.println("--------------------------------");
  46. System.out.println("");
  47. new Thread(new ClientThread()).start();
  48. } catch (IOException e) {
  49. e.printStackTrace();
  50. }
  51. }
  52. public static void sendMessage(String message){
  53. String moddedMessage = username + " wrote: " + message + "\n";
  54. try {
  55. DataOutputStream toServer = new DataOutputStream(sock.getOutputStream());
  56. toServer.writeBytes(moddedMessage);
  57. } catch (IOException e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. }