105 lines
2.3 KiB
Java
105 lines
2.3 KiB
Java
package uulm.teamname.marvelous.server.net;
|
|
|
|
import org.java_websocket.WebSocket;
|
|
import org.java_websocket.framing.CloseFrame;
|
|
import org.tinylog.Logger;
|
|
import uulm.teamname.marvelous.gamelibrary.messages.BasicMessage;
|
|
import uulm.teamname.marvelous.gamelibrary.messages.ErrorMessage;
|
|
import uulm.teamname.marvelous.gamelibrary.messages.ParticipantType;
|
|
|
|
import java.util.Optional;
|
|
|
|
@SuppressWarnings("UnusedReturnValue")
|
|
public class Client {
|
|
private final WebSocket socket;
|
|
private ClientState state = ClientState.Blank;
|
|
private SUID id = null;
|
|
private ParticipantType type = null;
|
|
private boolean ai = false;
|
|
|
|
public Client(WebSocket socket) {
|
|
this.socket = socket;
|
|
}
|
|
|
|
public boolean sendError(String error) {
|
|
ErrorMessage errorMessage = new ErrorMessage();
|
|
errorMessage.message = error;
|
|
return sendMessage(errorMessage);
|
|
}
|
|
|
|
public boolean sendMessage(BasicMessage message) {
|
|
if(socket == null) {
|
|
return false;
|
|
}
|
|
|
|
Optional<String> data = MarvelousServer.json.stringify(message);
|
|
|
|
if(data.isEmpty()) {
|
|
return false;
|
|
}
|
|
|
|
Logger.debug("Sending message to " + this + ": " + data.get()); //i hate java so much
|
|
|
|
try {
|
|
socket.send(data.get());
|
|
return true;
|
|
}catch (Exception ignored) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public boolean disconnect() {
|
|
if(socket == null) {
|
|
return false;
|
|
}
|
|
|
|
socket.close(CloseFrame.NORMAL);
|
|
return true;
|
|
}
|
|
|
|
public ClientState getState() {
|
|
return state;
|
|
}
|
|
|
|
public void setState(ClientState state) {
|
|
this.state = state;
|
|
}
|
|
|
|
public SUID getID() {
|
|
return id;
|
|
}
|
|
|
|
public void setID(SUID id) {
|
|
this.id = id;
|
|
}
|
|
|
|
public ParticipantType getType() {
|
|
return type;
|
|
}
|
|
|
|
public void setType(ParticipantType type) {
|
|
this.type = type;
|
|
}
|
|
|
|
public boolean isAI() {
|
|
return ai;
|
|
}
|
|
|
|
public void isAI(boolean ai) {
|
|
this.ai = ai;
|
|
}
|
|
|
|
public WebSocket getSocket() {
|
|
return socket;
|
|
}
|
|
|
|
@Override
|
|
public String toString() {
|
|
if(id != null) {
|
|
return id.toString();
|
|
}else {
|
|
return "Client@"+Integer.toHexString(hashCode());
|
|
}
|
|
}
|
|
}
|