chatprogramm was sonst
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.

67 lines
2.2 KiB

1 year ago
  1. package server.net;
  2. import server.Main;
  3. import server.util.CeasarChipher;
  4. import java.io.DataInputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.IOException;
  7. import java.net.Socket;
  8. public class ChatClient {
  9. private final int id;
  10. private final Socket s;
  11. private final DataInputStream inputStream;
  12. private final DataOutputStream outputStream;
  13. private final Thread t;
  14. public ChatClient(int id, Socket s, DataInputStream inputStream, DataOutputStream outputStream) {
  15. this.id = id;
  16. this.s = s;
  17. this.inputStream = inputStream;
  18. this.outputStream = outputStream;
  19. t = new Thread(() -> {
  20. try {
  21. while (true) {
  22. int len = inputStream.readInt();
  23. byte[] buf = new byte[len];
  24. inputStream.readFully(buf, 0, len);
  25. //TEST
  26. System.out.println(new String(CeasarChipher.decrypt(buf)));
  27. }
  28. } catch (IOException e) {
  29. Main.console.error("An error occurred while reading from client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
  30. e.printStackTrace();
  31. }
  32. });
  33. try {
  34. t.start();
  35. } catch (Throwable e) {
  36. Main.console.error("An error occurred while starting client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
  37. e.printStackTrace();
  38. }
  39. }
  40. public void write(byte[] buf) {
  41. try {
  42. outputStream.writeInt(buf.length);
  43. outputStream.write(CeasarChipher.encrypt(buf));
  44. } catch (Throwable e) {
  45. Main.console.error("An error occurred while writing data to client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
  46. e.printStackTrace();
  47. }
  48. }
  49. public void disconnect() {
  50. try {
  51. t.stop();
  52. s.close();
  53. inputStream.close();
  54. outputStream.close();
  55. } catch (Throwable e) {
  56. Main.console.error("An error occurred while disconnecting client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
  57. e.printStackTrace();
  58. }
  59. }
  60. }