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.
69 lines
2.0 KiB
69 lines
2.0 KiB
package visualiser.gameController;
|
|
|
|
import network.BinaryMessageEncoder;
|
|
import network.MessageEncoders.RaceVisionByteEncoder;
|
|
import network.Messages.BoatAction;
|
|
import network.Messages.Enums.BoatActionEnum;
|
|
import network.Messages.Enums.MessageType;
|
|
import visualiser.gameController.Keys.ControlKey;
|
|
|
|
import java.io.DataOutputStream;
|
|
import java.io.IOException;
|
|
import java.net.Socket;
|
|
import java.net.SocketException;
|
|
import java.nio.ByteBuffer;
|
|
|
|
/**
|
|
* Basic service for sending key presses to game server
|
|
*/
|
|
public class ControllerClient {
|
|
/**
|
|
* Socket to server
|
|
*/
|
|
Socket socket;
|
|
|
|
/**
|
|
* Output stream wrapper for socket to server
|
|
*/
|
|
DataOutputStream outputStream;
|
|
|
|
/**
|
|
* Initialise controller client with live socket.
|
|
* @param socket to server
|
|
*/
|
|
public ControllerClient(Socket socket) {
|
|
this.socket = socket;
|
|
|
|
try {
|
|
this.outputStream = new DataOutputStream(socket.getOutputStream());
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Send a keypress to server
|
|
* @param key to send
|
|
* @throws IOException if socket write fails
|
|
*/
|
|
public void sendKey(ControlKey key) throws IOException {
|
|
BoatActionEnum protocolCode = key.getProtocolCode();
|
|
if(protocolCode != BoatActionEnum.NOT_A_STATUS) {
|
|
|
|
byte[] bytes = new byte[4];
|
|
ByteBuffer.wrap(bytes).putInt(protocolCode.getValue());
|
|
BoatActionEnum boatActionEnum = BoatActionEnum.fromByte(bytes[3]);
|
|
|
|
BoatAction boatAction = new BoatAction(boatActionEnum);
|
|
|
|
byte[] encodedBoatAction = RaceVisionByteEncoder.boatActionMessage(boatAction);
|
|
|
|
BinaryMessageEncoder binaryMessage = new BinaryMessageEncoder(MessageType.BOATACTION, System.currentTimeMillis(), 0,
|
|
(short) encodedBoatAction.length, encodedBoatAction);
|
|
|
|
System.out.println("Sending out key: " + boatActionEnum);
|
|
outputStream.write(binaryMessage.getFullMessage());
|
|
}
|
|
}
|
|
}
|