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.

60 lines
1.9 KiB

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);
  27. n_users++;
  28. }
  29. } catch (IOException e) {
  30. Main.console.error("An error occurred while listening for connections!");
  31. e.printStackTrace();
  32. }
  33. });
  34. id_q = new Queue<>(max_users);
  35. for (int i = 0; i < max_users; ++i) id_q.enq(i);
  36. }
  37. public void start() {
  38. try {
  39. server = new ServerSocket(port);
  40. t.start();
  41. } catch (Throwable e) {
  42. Main.console.error("An error occurred while starting the ChatServer!");
  43. e.printStackTrace();
  44. }
  45. }
  46. public void stop() {
  47. try {
  48. t.stop();
  49. } catch (Throwable e) {
  50. Main.console.error("An error occurred while stopping the ChatServer!");
  51. e.printStackTrace();
  52. }
  53. }
  54. }