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.

69 lines
2.2 KiB

package server.net;
import server.Main;
import server.util.Queue;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
private final int port;
private volatile int n_users;
private final Thread t;
private ServerSocket server;
private Queue<Integer> id_q;
public ChatServer(int port, int max_users) {
Main.console.info("Initializing server on port: " + port + " with max_users: " + max_users);
this.port = port;
n_users = 0;
t = new Thread(() -> {
try {
while (true) {
if (n_users == max_users) continue;
Socket s = server.accept();
DataInputStream inputStream = new DataInputStream(s.getInputStream());
DataOutputStream outputStream = new DataOutputStream(s.getOutputStream());
ChatClient client = new ChatClient(id_q.deq(), s, inputStream, outputStream, this);
n_users++;
Main.console.success("Client (" + s.getRemoteSocketAddress().toString() + ") [id: " + client.id + "] connected!");
}
} catch (IOException e) {
Main.console.error("An error occurred while listening for connections!");
e.printStackTrace();
}
});
id_q = new Queue<>(max_users);
for (int i = 0; i < max_users; ++i) id_q.enq(i);
}
public void start() {
try {
server = new ServerSocket(port);
t.start();
} catch (Throwable e) {
Main.console.error("An error occurred while starting the ChatServer!");
e.printStackTrace();
}
}
public void stop() {
try {
t.stop();
} catch (Throwable e) {
Main.console.error("An error occurred while stopping the ChatServer!");
e.printStackTrace();
}
}
public void disconnect(ChatClient c) {
c.disconnect();
id_q.enq(c.id);
n_users--;
Main.console.info("Disconnected client [id: " + c.id + "]");
}
}