ChernoChat
ChernoChat copied to clipboard
Kick not working properly
disconnected clients can still send Messages to everyone
FIX: Send Function in clientWindow.Java
private void send(String message, boolean text) {
if (message.equals("")) return;
if (text) {
//removed this line cause we'll handle that in the server from now
message = "/m/" + client.getID() + "/s/" + message + "/e/"; // I used s since it is the first letter of start of message but you can use anything you like
txtMessage.setText("");
}
client.send(message.getBytes());
}
Process function in Server.Java
private void process(DatagramPacket packet) {
String string = new String(packet.getData());
if (raw) System.out.println(string);
if (string.startsWith("/c/")) {
// UUID id = UUID.randomUUID();
int id = UniqueIdentifier.getIdentifier();
String name = string.split("/c/|/e/")[1];
System.out.println(name + "(" + id + ") connected!");
clients.add(new ServerClient(name, packet.getAddress(), packet.getPort(), id));
String ID = "/c/" + id;
send(ID, packet.getAddress(), packet.getPort());
} else if (string.startsWith("/m/")) {
// Part I changed --------------------------------------------------------
int id;
String s_id = string.split("/m/|/s/")[1];
String name = null;
try {
id = Integer.parseInt(s_id);
} catch (NumberFormatException e) {
//wrong format
return;
}
for (int i = 0; i < clients.size(); i++) {
if (clients.get(i).getID() == id) {
name = clients.get(i).name;
break;
}
}
if (name != null) sendToAll("/m/" + name + ": " string.split("/s/|/e/")[1] + "/e/");
// -------------------------------------------------------------------------
} else if (string.startsWith("/d/")) {
String id = string.split("/d/|/e/")[1];
disconnect(Integer.parseInt(id), true);
} else if (string.startsWith("/i/")) {
clientResponse.add(Integer.parseInt(string.split("/i/|/e/")[1]));
} else {
System.out.println(string);
}
}
Nice fix! I did something similar.
I did find myself doing that search over in different parts of the code, so I wrote getClient()
private ServerClient getClient(int id){
ServerClient c = null;
for (int i = 0; i < clients.size(); i++) {
if (clients.get(i).getID() == id) {
c = clients.get(i);
break;
}
}
return c;
}
It returns either the client object, or null if the object is not in the list.
Then I also made a version that takes a string:
private ServerClient getClient(String name){
ServerClient c = null;
name = name.toLowerCase();
int id = -1;
try { // Create an Int id if possible
id = Integer.parseInt(name);
} catch (NumberFormatException e) {
}
// Search for either id or name match
for (int i = 0; i < clients.size(); i++) {
if (clients.get(i).getID() == id || clients.get(i).name.toLowerCase().equals(name)) {
c = clients.get(i);
break;
}
}
return c;
}
This is useful for the kick feature. It is case insensitive, and it will search on ID or name, so "/kick 12345" will find a user named "12345" or a user with the ID 12345 (whichever it finds first).