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.

71 lines
2.3 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 {
final int id;
private final Socket s;
private final DataInputStream inputStream;
private final DataOutputStream outputStream;
private final Thread t;
private final ChatServer server;
public ChatClient(int id, Socket s, DataInputStream inputStream, DataOutputStream outputStream, ChatServer server) {
this.id = id;
this.s = s;
this.inputStream = inputStream;
this.outputStream = outputStream;
this.server = server;
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();
server.disconnect(this);
}
});
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();
}
}
}