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
68 lines
2.2 KiB
package server.net;
|
|
|
|
import server.Main;
|
|
import server.util.CeasarChipher;
|
|
|
|
import java.io.DataInputStream;
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.net.Socket;
|
|
|
|
public class ChatClient {
|
|
|
|
private final int id;
|
|
private final Socket s;
|
|
private final DataInputStream inputStream;
|
|
private final DataOutputStream outputStream;
|
|
private final Thread t;
|
|
|
|
public ChatClient(int id, Socket s, DataInputStream inputStream, DataOutputStream outputStream) {
|
|
this.id = id;
|
|
this.s = s;
|
|
this.inputStream = inputStream;
|
|
this.outputStream = outputStream;
|
|
t = new Thread(() -> {
|
|
try {
|
|
while (true) {
|
|
int len = inputStream.readInt();
|
|
byte[] buf = new byte[len];
|
|
inputStream.readFully(buf, 0, len);
|
|
|
|
//TEST
|
|
System.out.println(new String(CeasarChipher.decrypt(buf)));
|
|
}
|
|
} catch (IOException e) {
|
|
Main.console.error("An error occurred while reading from client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
|
|
e.printStackTrace();
|
|
}
|
|
});
|
|
try {
|
|
t.start();
|
|
} catch (Throwable e) {
|
|
Main.console.error("An error occurred while starting client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public void write(byte[] buf) {
|
|
try {
|
|
outputStream.writeInt(buf.length);
|
|
outputStream.write(CeasarChipher.encrypt(buf));
|
|
} catch (Throwable e) {
|
|
Main.console.error("An error occurred while writing data to client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
public void disconnect() {
|
|
try {
|
|
t.stop();
|
|
s.close();
|
|
inputStream.close();
|
|
outputStream.close();
|
|
} catch (Throwable e) {
|
|
Main.console.error("An error occurred while disconnecting client (" + s.getRemoteSocketAddress().toString() + ") [id: " + id + "]");
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|