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.

70 lines
2.3 KiB

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