Browse Source

little bit

master
elikicker 2 years ago
parent
commit
af1e24d8c2
  1. 7
      crychat/server/net/ChatClient.java
  2. 10
      crychat/server/net/ChatServer.java

7
crychat/server/net/ChatClient.java

@ -10,17 +10,19 @@ import java.net.Socket;
public class ChatClient { public class ChatClient {
private final int id;
final int id;
private final Socket s; private final Socket s;
private final DataInputStream inputStream; private final DataInputStream inputStream;
private final DataOutputStream outputStream; private final DataOutputStream outputStream;
private final Thread t; private final Thread t;
private final ChatServer server;
public ChatClient(int id, Socket s, DataInputStream inputStream, DataOutputStream outputStream) {
public ChatClient(int id, Socket s, DataInputStream inputStream, DataOutputStream outputStream, ChatServer server) {
this.id = id; this.id = id;
this.s = s; this.s = s;
this.inputStream = inputStream; this.inputStream = inputStream;
this.outputStream = outputStream; this.outputStream = outputStream;
this.server = server;
t = new Thread(() -> { t = new Thread(() -> {
try { try {
while (true) { while (true) {
@ -34,6 +36,7 @@ public class ChatClient {
} catch (IOException e) { } catch (IOException e) {
Main.console.error("An error occurred while reading from client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]"); Main.console.error("An error occurred while reading from client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
e.printStackTrace(); e.printStackTrace();
server.disconnect(this);
} }
}); });
try { try {

10
crychat/server/net/ChatServer.java

@ -28,8 +28,9 @@ public class ChatServer {
Socket s = server.accept(); Socket s = server.accept();
DataInputStream inputStream = new DataInputStream(s.getInputStream()); DataInputStream inputStream = new DataInputStream(s.getInputStream());
DataOutputStream outputStream = new DataOutputStream(s.getOutputStream()); DataOutputStream outputStream = new DataOutputStream(s.getOutputStream());
ChatClient client = new ChatClient(id_q.deq(), s, inputStream, outputStream);
ChatClient client = new ChatClient(id_q.deq(), s, inputStream, outputStream, this);
n_users++; n_users++;
Main.console.success("Client (" + s.getRemoteSocketAddress().toString() + ") [id: " + client.id + "] connected!");
} }
} catch (IOException e) { } catch (IOException e) {
Main.console.error("An error occurred while listening for connections!"); Main.console.error("An error occurred while listening for connections!");
@ -58,4 +59,11 @@ public class ChatServer {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void disconnect(ChatClient c) {
c.disconnect();
id_q.enq(c.id);
n_users--;
Main.console.info("Disconnected client [id: " + c.id + "]");
}
} }
Loading…
Cancel
Save