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 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. id_q = new Queue<>(max_users);
  20. for (int i = 0; i < max_users; ++i) id_q.enq(i);
  21. t = new Thread(() -> {
  22. try {
  23. while (true) {
  24. if (n_users == max_users) continue;
  25. Socket s = server.accept();
  26. DataInputStream inputStream = new DataInputStream(s.getInputStream());
  27. DataOutputStream outputStream = new DataOutputStream(s.getOutputStream());
  28. ChatClient client = new ChatClient(id_q.deq(), s, inputStream, outputStream, this);
  29. n_users++;
  30. Main.console.success("Client (" + s.getRemoteSocketAddress().toString() + ") [id: " + client.id + "] connected!");
  31. }
  32. } catch (IOException e) {
  33. Main.console.error("An error occurred while listening for connections!");
  34. e.printStackTrace();
  35. }
  36. });
  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. }