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.

68 lines
2.2 KiB

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.Queue;
  4. import java.io.DataInputStream;
  5. import java.io.DataOutputStream;
  6. import java.io.IOException;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. public class ChatServer {
  10. private final int port;
  11. private volatile int n_users;
  12. private final Thread t;
  13. private ServerSocket server;
  14. private Queue<Integer> id_q;
  15. public ChatServer(int port, int max_users) {
  16. Main.console.info("Initializing server on port: " + port + " with max_users: " + max_users);
  17. this.port = port;
  18. n_users = 0;
  19. t = new Thread(() -> {
  20. try {
  21. while (true) {
  22. if (n_users == max_users) continue;
  23. Socket s = server.accept();
  24. DataInputStream inputStream = new DataInputStream(s.getInputStream());
  25. DataOutputStream outputStream = new DataOutputStream(s.getOutputStream());
  26. ChatClient client = new ChatClient(id_q.deq(), s, inputStream, outputStream, this);
  27. n_users++;
  28. Main.console.success("Client (" + s.getRemoteSocketAddress().toString() + ") [id: " + client.id + "] connected!");
  29. }
  30. } catch (IOException e) {
  31. Main.console.error("An error occurred while listening for connections!");
  32. e.printStackTrace();
  33. }
  34. });
  35. id_q = new Queue<>(max_users);
  36. for (int i = 0; i < max_users; ++i) id_q.enq(i);
  37. }
  38. public void start() {
  39. try {
  40. server = new ServerSocket(port);
  41. t.start();
  42. } catch (Throwable e) {
  43. Main.console.error("An error occurred while starting the ChatServer!");
  44. e.printStackTrace();
  45. }
  46. }
  47. public void stop() {
  48. try {
  49. t.stop();
  50. } catch (Throwable e) {
  51. Main.console.error("An error occurred while stopping the ChatServer!");
  52. e.printStackTrace();
  53. }
  54. }
  55. public void disconnect(ChatClient c) {
  56. c.disconnect();
  57. id_q.enq(c.id);
  58. n_users--;
  59. Main.console.info("Disconnected client [id: " + c.id + "]");
  60. }
  61. }