mirror of
https://github.com/michaelrausch/Party-Parrots-At-Sea.git
synced 2026-05-09 14:28:43 +00:00
Merge remote-tracking branch 'origin/develop' into develop
This commit is contained in:
@@ -7,8 +7,8 @@ import javafx.scene.Scene;
|
||||
import javafx.scene.image.Image;
|
||||
import javafx.stage.Stage;
|
||||
import seng302.client.ClientPacketParser;
|
||||
import seng302.client.ClientState;
|
||||
import seng302.models.PolarTable;
|
||||
import seng302.models.stream.StreamReceiver;
|
||||
|
||||
public class App extends Application {
|
||||
|
||||
@@ -27,10 +27,10 @@ public class App extends Application {
|
||||
primaryStage.show();
|
||||
primaryStage.setOnCloseRequest(e -> {
|
||||
ClientPacketParser.appClose();
|
||||
StreamReceiver.noMoreBytes();
|
||||
System.exit(0);
|
||||
});
|
||||
|
||||
ClientState.primaryStage = primaryStage;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
@@ -108,7 +108,6 @@ public class ClientPacketParser {
|
||||
}
|
||||
} catch (NullPointerException e) {
|
||||
System.out.println("Error parsing packet");
|
||||
// e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -287,7 +286,7 @@ public class ClientPacketParser {
|
||||
db = dbf.newDocumentBuilder();
|
||||
doc = db.parse(new InputSource(new StringReader(xmlMessage)));
|
||||
} catch (ParserConfigurationException | IOException | SAXException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[ClientPacketParser] ParserConfigurationException | IOException | SAXException");
|
||||
}
|
||||
|
||||
xmlObject.constructXML(doc, messageType);
|
||||
|
||||
@@ -2,6 +2,7 @@ package seng302.client;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import javafx.stage.Stage;
|
||||
import seng302.models.Yacht;
|
||||
|
||||
/**
|
||||
@@ -17,6 +18,7 @@ public class ClientState {
|
||||
private static Map<Integer, Yacht> boats = new ConcurrentHashMap<>();
|
||||
private static Boolean boatsUpdated = true;
|
||||
private static String clientSourceId = "";
|
||||
public static Stage primaryStage;
|
||||
|
||||
public static String getHostIp() {
|
||||
return hostIp;
|
||||
|
||||
@@ -26,7 +26,7 @@ public class ClientStateQueryingRunnable extends Observable implements Runnable
|
||||
try {
|
||||
Thread.sleep(0);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ClientState.isRaceStarted() && ClientState.isConnectedToHost()) {
|
||||
|
||||
@@ -10,6 +10,9 @@ import java.time.LocalDateTime;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Checksum;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.Alert.AlertType;
|
||||
import seng302.models.stream.packets.StreamPacket;
|
||||
import seng302.server.messages.BoatActionMessage;
|
||||
import seng302.server.messages.Message;
|
||||
@@ -42,7 +45,8 @@ public class ClientToServerThread implements Runnable {
|
||||
*
|
||||
* @param ipAddress a string of ip address to be connected to
|
||||
* @param portNumber an integer port number
|
||||
* @throws Exception SocketConnection if fail to connect to ip address and port number combination
|
||||
* @throws Exception SocketConnection if fail to connect to ip address and port number
|
||||
* combination
|
||||
*/
|
||||
public ClientToServerThread(String ipAddress, Integer portNumber) throws Exception {
|
||||
socket = new Socket(ipAddress, portNumber);
|
||||
@@ -73,7 +77,8 @@ public class ClientToServerThread implements Runnable {
|
||||
*/
|
||||
static void clientLog(String message, int logLevel) {
|
||||
if (logLevel <= LOG_LEVEL) {
|
||||
System.out.println("[CLIENT " + LocalDateTime.now().toLocalTime().toString() + "] " + message);
|
||||
System.out.println(
|
||||
"[CLIENT " + LocalDateTime.now().toLocalTime().toString() + "] " + message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,6 +116,15 @@ public class ClientToServerThread implements Runnable {
|
||||
}
|
||||
} catch (Exception e) {
|
||||
closeSocket();
|
||||
Platform.runLater(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Alert alert = new Alert(AlertType.ERROR);
|
||||
alert.setHeaderText("Host has disconnected");
|
||||
alert.setContentText("Cannot find Server");
|
||||
alert.showAndWait();
|
||||
}
|
||||
});
|
||||
clientLog("Disconnected from server", 1);
|
||||
return;
|
||||
}
|
||||
@@ -122,6 +136,7 @@ public class ClientToServerThread implements Runnable {
|
||||
|
||||
/**
|
||||
* Listens for an allocated sourceID and returns it to the server
|
||||
*
|
||||
* @return the sourceID allocated to us by the server
|
||||
*/
|
||||
private Integer threeWayHandshake() {
|
||||
@@ -146,7 +161,6 @@ public class ClientToServerThread implements Runnable {
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Send the post-start race course information
|
||||
*/
|
||||
|
||||
@@ -181,9 +181,9 @@ public class CanvasController {
|
||||
contentPane.getChildren().addAll(
|
||||
(Pane) FXMLLoader.load(getClass().getResource("/views/FinishScreenView.fxml")));
|
||||
} catch (javafx.fxml.LoadException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] FXML load exception");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] IO exception");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,9 +282,8 @@ public class CanvasController {
|
||||
p2d.getX(), p2d.getY(), heading, positionPacket.getGroundSpeed(),
|
||||
positionPacket.getTimeValid(), frameRate);
|
||||
} catch (InterruptedException e){
|
||||
e.printStackTrace();
|
||||
System.out.println("[CanvasController] Interrupted Exception");
|
||||
}
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -297,7 +296,7 @@ public class CanvasController {
|
||||
Point2D p2d = findScaledXY(positionPacket.getLat(), positionPacket.getLon());
|
||||
markGroup.moveMarkTo(p2d.getX(), p2d.getY(), raceId);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[CanvasController] Interrupted exception");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import javafx.scene.Parent;
|
||||
import javafx.scene.input.KeyEvent;
|
||||
import javafx.scene.layout.AnchorPane;
|
||||
import seng302.client.ClientPacketParser;
|
||||
import seng302.client.ClientState;
|
||||
import seng302.client.ClientToServerThread;
|
||||
import seng302.server.messages.BoatActionMessage;
|
||||
import seng302.server.messages.BoatActionType;
|
||||
@@ -22,7 +23,7 @@ public class Controller implements Initializable {
|
||||
private long lastSendingTime;
|
||||
private int KEY_STROKE_SENDING_FREQUENCY = 50;
|
||||
|
||||
private Object setContentPane(String jfxUrl) {
|
||||
public Object setContentPane(String jfxUrl) {
|
||||
try {
|
||||
contentPane.getChildren().removeAll();
|
||||
contentPane.getChildren().clear();
|
||||
@@ -41,19 +42,25 @@ public class Controller implements Initializable {
|
||||
|
||||
@Override
|
||||
public void initialize(URL location, ResourceBundle resources) {
|
||||
setUpStartScreen();
|
||||
lastSendingTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
void setUpStartScreen() {
|
||||
contentPane.getChildren().removeAll();
|
||||
contentPane.getChildren().clear();
|
||||
contentPane.getStylesheets().add(getClass().getResource("/css/master.css").toString());
|
||||
StartScreenController startScreenController = (StartScreenController) setContentPane("/views/StartScreenView.fxml");
|
||||
startScreenController.setController(this);
|
||||
ClientPacketParser.boatLocations.clear();
|
||||
|
||||
lastSendingTime = System.currentTimeMillis();
|
||||
}
|
||||
|
||||
|
||||
/** Handle the key-pressed event from the text field. */
|
||||
public void keyPressed(KeyEvent e) {
|
||||
BoatActionMessage boatActionMessage;
|
||||
long currentTime = System.currentTimeMillis();
|
||||
if (currentTime - lastSendingTime > KEY_STROKE_SENDING_FREQUENCY) {
|
||||
if (currentTime - lastSendingTime > KEY_STROKE_SENDING_FREQUENCY && ClientState.isRaceStarted()) {
|
||||
lastSendingTime = currentTime;
|
||||
switch (e.getCode()) {
|
||||
case SPACE: // align with vmg
|
||||
|
||||
@@ -85,9 +85,9 @@ public class FinishScreenViewController implements Initializable {
|
||||
contentPane.getChildren()
|
||||
.addAll((Pane) FXMLLoader.load(getClass().getResource(jfxUrl)));
|
||||
} catch (javafx.fxml.LoadException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] FXML load exception");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] IO exception");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,6 +85,7 @@ public class LobbyController implements Initializable, Observer{
|
||||
|
||||
private Boolean switchedPane = false;
|
||||
private MainServerThread mainServerThread;
|
||||
private Controller controller;
|
||||
|
||||
private void setContentPane(String jfxUrl) {
|
||||
try {
|
||||
@@ -95,9 +96,11 @@ public class LobbyController implements Initializable, Observer{
|
||||
contentPane.getChildren()
|
||||
.addAll((Pane) FXMLLoader.load(getClass().getResource(jfxUrl)));
|
||||
} catch (javafx.fxml.LoadException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] FXML load exception");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] IO exception");
|
||||
} catch (NullPointerException e) {
|
||||
// System.out.println("[Controller] Null Pointer Exception");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,7 +111,7 @@ public class LobbyController implements Initializable, Observer{
|
||||
readyButton.setDisable(false);
|
||||
}
|
||||
else {
|
||||
lobbyIpText.setText("Connected to IP: ");
|
||||
lobbyIpText.setText("Connected to IP: " + ClientState.getHostIp());
|
||||
readyButton.setDisable(true);
|
||||
}
|
||||
|
||||
@@ -200,11 +203,12 @@ public class LobbyController implements Initializable, Observer{
|
||||
|
||||
@FXML
|
||||
public void leaveLobbyButtonPressed() {
|
||||
// TODO: 10/07/17 wmu16 - Finish function!
|
||||
setContentPane("/views/StartScreenView.fxml");
|
||||
if (ClientState.isHost()) {
|
||||
GameState.setCurrentStage(GameStages.CANCELLED);
|
||||
// TODO: 20/07/17 wmu16 - Implement some way of terminating the game
|
||||
mainServerThread.terminate();
|
||||
}
|
||||
ClientState.setConnectedToHost(false);
|
||||
controller.setUpStartScreen();
|
||||
}
|
||||
|
||||
@FXML
|
||||
@@ -224,4 +228,8 @@ public class LobbyController implements Initializable, Observer{
|
||||
public void setMainServerThread(MainServerThread mainServerThread) {
|
||||
this.mainServerThread = mainServerThread;
|
||||
}
|
||||
|
||||
public void setController(Controller controller) {
|
||||
this.controller = controller;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ public class RaceViewController extends Thread implements ImportantAnnotationDel
|
||||
controller.loadState(importantAnnotations);
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[RaceViewController] IO exception");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,9 +51,9 @@ public class StartScreenController {
|
||||
|
||||
return fxmlLoader.getController();
|
||||
} catch (javafx.fxml.LoadException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] FXML load exception");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Controller] IO exception");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -81,12 +81,12 @@ public class StartScreenController {
|
||||
controller.setClientToServerThread(clientToServerThread);
|
||||
LobbyController lobbyController = (LobbyController) setContentPane("/views/LobbyView.fxml");
|
||||
lobbyController.setMainServerThread(mainServerThread);
|
||||
lobbyController.setController(controller);
|
||||
} catch (Exception e) {
|
||||
Alert alert = new Alert(AlertType.ERROR);
|
||||
alert.setHeaderText("Cannot host");
|
||||
alert.setContentText("Oops, failed to host, try to restart.");
|
||||
alert.showAndWait();
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
@@ -109,8 +109,10 @@ public class StartScreenController {
|
||||
ClientState.setHost(false);
|
||||
ClientState.setConnectedToHost(true);
|
||||
|
||||
ClientState.setHostIp(ipAddress);
|
||||
controller.setClientToServerThread(clientToServerThread);
|
||||
setContentPane("/views/LobbyView.fxml");
|
||||
LobbyController lobbyController = (LobbyController) setContentPane("/views/LobbyView.fxml");
|
||||
lobbyController.setController(controller);
|
||||
} catch (Exception e) {
|
||||
Alert alert = new Alert(AlertType.ERROR);
|
||||
alert.setHeaderText("Cannot reach the host");
|
||||
@@ -151,7 +153,7 @@ public class StartScreenController {
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[StartScreenController] Exception");
|
||||
}
|
||||
if (ipAddress == null) {
|
||||
System.out.println("[HOST] Cannot obtain local host ip address.");
|
||||
|
||||
@@ -33,10 +33,6 @@ public class GameState implements Runnable {
|
||||
public GameState(String hostIpAddress) {
|
||||
windDirection = 180d;
|
||||
windSpeed = 10000d;
|
||||
yachts = new HashMap<>();
|
||||
players = new ArrayList<>();
|
||||
|
||||
|
||||
this.hostIpAddress = hostIpAddress;
|
||||
players = new ArrayList<>();
|
||||
currentStage = GameStages.LOBBYING;
|
||||
@@ -140,13 +136,7 @@ public class GameState implements Runnable {
|
||||
break;
|
||||
}
|
||||
|
||||
System.out.println("-----------------------");
|
||||
System.out.println("Sails are in: " + playerYacht.getSailIn());
|
||||
System.out.println("Heading: " + playerYacht.getHeading());
|
||||
System.out.println("Velocity: " + playerYacht.getVelocityMMS() / 1000);
|
||||
System.out.println("Lat: " + playerYacht.getLocation().getLat());
|
||||
System.out.println("Lng: " + playerYacht.getLocation().getLng());
|
||||
System.out.println("-----------------------\n");
|
||||
// printBoatStatus(playerYacht);
|
||||
}
|
||||
|
||||
public static void update() {
|
||||
@@ -178,7 +168,7 @@ public class GameState implements Runnable {
|
||||
try {
|
||||
Thread.sleep(1000 / STATE_UPDATES_PER_SECOND);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[GameState] interrupted exception");
|
||||
}
|
||||
if (currentStage == GameStages.PRE_RACE) {
|
||||
update();
|
||||
@@ -190,4 +180,14 @@ public class GameState implements Runnable {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void printBoatStatus(Yacht playerYacht) {
|
||||
System.out.println("-----------------------");
|
||||
System.out.println("Sails are in: " + playerYacht.getSailIn());
|
||||
System.out.println("Heading: " + playerYacht.getHeading());
|
||||
System.out.println("Velocity: " + playerYacht.getVelocityMMS() / 1000);
|
||||
System.out.println("Lat: " + playerYacht.getLocation().getLat());
|
||||
System.out.println("Lng: " + playerYacht.getLocation().getLng());
|
||||
System.out.println("-----------------------\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ public class MainServerThread extends Observable implements Runnable, ClientConn
|
||||
private static final int PORT = 4942;
|
||||
private static final Integer CLIENT_UPDATES_PER_SECOND = 10;
|
||||
private static final int LOG_LEVEL = 1;
|
||||
private boolean terminated;
|
||||
|
||||
private Thread thread;
|
||||
|
||||
@@ -38,6 +39,7 @@ public class MainServerThread extends Observable implements Runnable, ClientConn
|
||||
serverLog("IO error in server thread handler upon trying to make new server socket", 0);
|
||||
}
|
||||
|
||||
terminated = false;
|
||||
thread = new Thread(this);
|
||||
thread.start();
|
||||
}
|
||||
@@ -54,11 +56,11 @@ public class MainServerThread extends Observable implements Runnable, ClientConn
|
||||
serverListenThread.start();
|
||||
|
||||
//You should handle interrupts in some way, so that the thread won't keep on forever if you exit the app.
|
||||
while (!thread.isInterrupted()) {
|
||||
while (!terminated) {
|
||||
try {
|
||||
Thread.sleep(1000 / CLIENT_UPDATES_PER_SECOND);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
serverLog("Interrupted exception in Main Server Thread thread sleep", 1);
|
||||
}
|
||||
|
||||
if (GameState.getCurrentStage() == GameStages.PRE_RACE) {
|
||||
@@ -148,4 +150,8 @@ public class MainServerThread extends Observable implements Runnable, ClientConn
|
||||
}
|
||||
}, 0, 500);
|
||||
}
|
||||
|
||||
public void terminate() {
|
||||
terminated = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,9 +27,11 @@ public class ServerListenThread extends Thread{
|
||||
private void acceptConnection() {
|
||||
try {
|
||||
Socket thisClient = serverSocket.accept();
|
||||
if (thisClient != null){
|
||||
if (thisClient != null && GameState.getCurrentStage().equals(GameStages.LOBBYING)) {
|
||||
ServerToClientThread thisConnection = new ServerToClientThread(thisClient);
|
||||
delegate.clientConnected(thisConnection);
|
||||
} else {
|
||||
thisClient.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.getMessage();
|
||||
|
||||
@@ -96,13 +96,12 @@ public class ServerToClientThread implements Runnable, Observer {
|
||||
all = ln.lines().collect(Collectors.toList());
|
||||
lName = all.get(ThreadLocalRandom.current().nextInt(0, all.size()));
|
||||
} catch (IOException e) {
|
||||
System.out.println("IO error in server thread upon grabbing streams");
|
||||
e.printStackTrace();
|
||||
serverLog("IO error in server thread upon grabbing streams", 1);
|
||||
}
|
||||
//Attempt threeway handshake with connection
|
||||
sourceId = GameState.getUniquePlayerID();
|
||||
if (threeWayHandshake(sourceId)) {
|
||||
serverLog("Successful handshake. Client allocated id: " + sourceId, 1);
|
||||
serverLog("Successful handshake. Client allocated id: " + sourceId, 0);
|
||||
Yacht yacht = new Yacht(
|
||||
"Yacht", sourceId, sourceId.toString(), fName, fName + " " + lName, "NZ"
|
||||
);
|
||||
@@ -186,7 +185,6 @@ public class ServerToClientThread implements Runnable, Observer {
|
||||
} catch (Exception e) {
|
||||
// TODO: 24/07/17 zyt10 - fix a logic here when a client disconnected
|
||||
// serverLog("ERROR OCCURRED, CLOSING SERVER CONNECTION: " + socket.getRemoteSocketAddress().toString(), 1);
|
||||
// e.printStackTrace();
|
||||
closeSocket();
|
||||
return;
|
||||
}
|
||||
@@ -243,7 +241,7 @@ public class ServerToClientThread implements Runnable, Observer {
|
||||
os.write(id); //Send out new ID looking for echo
|
||||
confirmationID = is.read();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
serverLog("Three way handshake failed", 1);
|
||||
}
|
||||
|
||||
if (id.equals(confirmationID)) { //ID is echoed back. Connection is a client
|
||||
@@ -273,7 +271,7 @@ public class ServerToClientThread implements Runnable, Observer {
|
||||
currentByte = is.read();
|
||||
crcBuffer.write(currentByte);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
serverLog("Socket read failed", 1);
|
||||
}
|
||||
if (currentByte == -1) {
|
||||
throw new Exception();
|
||||
@@ -299,10 +297,10 @@ public class ServerToClientThread implements Runnable, Observer {
|
||||
try {
|
||||
os.write(message.getBuffer());
|
||||
} catch (SocketException e) {
|
||||
//serverLog("Player " + sourceId + " side socket disconnected", 0);
|
||||
//serverLog("Player " + sourceId + " side socket disconnected", 1);
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
serverLog("Message send failed", 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ public final class PolarTable {
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[PolarTable] IO exception");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ public class CanvasMap {
|
||||
|
||||
return new Image(connection.getInputStream());
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[CanvasMap] Exception");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
package seng302.models.stream;
|
||||
|
||||
import seng302.models.stream.packets.StreamPacket;
|
||||
import seng302.server.messages.BoatActionMessage;
|
||||
import seng302.server.messages.BoatActionType;
|
||||
import seng302.server.messages.Heartbeat;
|
||||
import seng302.server.messages.Message;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.Comparator;
|
||||
import java.util.concurrent.PriorityBlockingQueue;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.Checksum;
|
||||
|
||||
|
||||
public class StreamReceiver extends Thread {
|
||||
private InputStream inputStream;
|
||||
private OutputStream outputStream;
|
||||
private Socket host;
|
||||
private ByteArrayOutputStream crcBuffer;
|
||||
private Thread t;
|
||||
private String threadName;
|
||||
public static PriorityBlockingQueue<StreamPacket> packetBuffer;
|
||||
private static boolean moreBytes;
|
||||
|
||||
public StreamReceiver(String hostAddress, int hostPort, String threadName) {
|
||||
this.threadName = threadName;
|
||||
this.setDaemon(true);
|
||||
try {
|
||||
host = new Socket(hostAddress, hostPort);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
public void run(){
|
||||
PriorityBlockingQueue<StreamPacket> pq = new PriorityBlockingQueue<>(256, new Comparator<StreamPacket>() {
|
||||
@Override
|
||||
public int compare(StreamPacket s1, StreamPacket s2) {
|
||||
return (int) (s1.getTimeStamp() - s2.getTimeStamp());
|
||||
}
|
||||
});
|
||||
packetBuffer = pq;
|
||||
connect();
|
||||
}
|
||||
|
||||
public void start () {
|
||||
if (t == null) {
|
||||
t = new Thread (this, threadName);
|
||||
t.start ();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public StreamReceiver(Socket host, PriorityBlockingQueue packetBuffer){
|
||||
this.host=host;
|
||||
this.packetBuffer = packetBuffer;
|
||||
}
|
||||
|
||||
|
||||
public void connect(){
|
||||
|
||||
// int sync1;
|
||||
// int sync2;
|
||||
// moreBytes = true;
|
||||
// while(moreBytes) {
|
||||
// try {
|
||||
// crcBuffer = new ByteArrayOutputStream();
|
||||
// sync1 = readByte();
|
||||
// sync2 = readByte();
|
||||
// //checking if it is the start of the packet
|
||||
// if(sync1 == 0x47 && sync2 == 0x83) {
|
||||
// int type = readByte();
|
||||
// //No. of milliseconds since Jan 1st 1970
|
||||
// long timeStamp = bytesToLong(getBytes(6));
|
||||
// skipBytes(4);
|
||||
// long payloadLength = bytesToLong(getBytes(2));
|
||||
// byte[] payload = getBytes((int) payloadLength);
|
||||
// Checksum checksum = new CRC32();
|
||||
// checksum.update(crcBuffer.toByteArray(), 0, crcBuffer.size());
|
||||
// long computedCrc = checksum.getValue();
|
||||
// long packetCrc = bytesToLong(getBytes(4));
|
||||
// if (computedCrc == packetCrc) {
|
||||
// packetBuffer.add(new StreamPacket(type, payloadLength, timeStamp, payload));
|
||||
// } else {
|
||||
// System.err.println("Packet has been dropped");
|
||||
// }
|
||||
// }
|
||||
// } catch (Exception e) {
|
||||
// moreBytes = false;
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
private int readByte() throws Exception {
|
||||
int currentByte = -1;
|
||||
try {
|
||||
currentByte = inputStream.read();
|
||||
crcBuffer.write(currentByte);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (currentByte == -1){
|
||||
throw new Exception();
|
||||
}
|
||||
return currentByte;
|
||||
}
|
||||
|
||||
private byte[] getBytes(int n) throws Exception{
|
||||
byte[] bytes = new byte[n];
|
||||
for (int i = 0; i < n; i++){
|
||||
bytes[i] = (byte) readByte();
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private void skipBytes(long n) throws Exception{
|
||||
for (int i=0; i < n; i++){
|
||||
readByte();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* takes an array of up to 7 bytes in little endian format and
|
||||
* returns a positive long constructed from the input bytes
|
||||
*
|
||||
* @return a positive long if there is less than 8 bytes -1 otherwise
|
||||
*/
|
||||
private long bytesToLong(byte[] bytes){
|
||||
long partialLong = 0;
|
||||
int index = 0;
|
||||
for (byte b: bytes){
|
||||
if (index > 6){
|
||||
return -1;
|
||||
}
|
||||
partialLong = partialLong | (b & 0xFFL) << (index * 8);
|
||||
index++;
|
||||
}
|
||||
return partialLong;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
StreamReceiver sr = new StreamReceiver("csse-s302staff.canterbury.ac.nz", 4941,"TestThread1");
|
||||
//StreamReceiver sr = new StreamReceiver("livedata.americascup.com", 4941, "TestThread2");
|
||||
sr.start();
|
||||
|
||||
}
|
||||
|
||||
public static void noMoreBytes(){
|
||||
moreBytes = false;
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ public class Simulator extends Observable implements Runnable {
|
||||
try {
|
||||
Thread.sleep(lapse);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[Simulator] interrupted exception ");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ public abstract class FileParser {
|
||||
doc.getDocumentElement().normalize();
|
||||
return doc;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[FileParser] Exception");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public abstract class FileParser {
|
||||
doc.getDocumentElement().normalize();
|
||||
return doc;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println("[FileParser] Exception");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
package seng302.models.stream;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.Socket;
|
||||
import java.util.Comparator;
|
||||
import java.util.concurrent.PriorityBlockingQueue;
|
||||
import seng302.models.stream.packets.StreamPacket;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Created by ptg19 on 26/04/17.
|
||||
*/
|
||||
public class StreamReceiverTest {
|
||||
|
||||
private PriorityBlockingQueue pq;
|
||||
private byte[] brokenPacket = {0x47, (byte) 0x83, 37, // sync1 sync2 and message type
|
||||
0b00000000, 0b01000000, 0b00100010, 0b00100100, 0b00011000, 0b00000000, //timestamp
|
||||
0b00000000, 0b00010000, 0b01000000, 0b00000000, //source id
|
||||
0b00100010, 0b00101000, // message length
|
||||
0b00010010, 0b00010010, 0b00010010}; //random start of payload
|
||||
|
||||
private byte[] workingPacket = {0x47, (byte) 0x83, 37, // sync1 sync2 and message type
|
||||
0b00000000, 0b01000000, 0b00100010, 0b00100100, 0b00011000, 0b00000000, //timestamp
|
||||
0b00000000, 0b00010000, 0b01000000, 0b00000000, //source id
|
||||
0b00000010, 0b00000000, // message length
|
||||
0b00010010, 0b00010010, // payload
|
||||
0b00100110, (byte)0b10000111, 0b00110101, 0b01111000}; //crc
|
||||
|
||||
private byte[] crcMismatchPacket = {0x47, (byte) 0x83, 37, // sync1 sync2 and message type
|
||||
0b00000000, 0b01000000, 0b00100010, 0b00100100, 0b00011000, 0b00000000, //timestamp
|
||||
0b00000000, 0b00000000, 0b01000000, 0b00000000, //source id
|
||||
0b00000010, 0b00000000, // message length
|
||||
0b00010010, 0b00010010, // payload
|
||||
0b00100110, (byte)0b10000111, 0b00110101, 0b01111000}; //crc
|
||||
|
||||
|
||||
@Before
|
||||
public void setup(){
|
||||
pq = new PriorityBlockingQueue<>(256, new Comparator<StreamPacket>() {
|
||||
@Override
|
||||
public int compare(StreamPacket s1, StreamPacket s2) {
|
||||
return (int) (s1.getTimeStamp() - s2.getTimeStamp());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void connectExitsOnUnexpectedStreamEnd() throws Exception {
|
||||
Socket host=mock(Socket.class);
|
||||
InputStream stream = new ByteArrayInputStream(brokenPacket);
|
||||
when(host.getInputStream()).thenReturn(stream);
|
||||
StreamReceiver streamReceiver = new StreamReceiver(host, pq);
|
||||
|
||||
streamReceiver.connect();
|
||||
assert pq.size() == 0;
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void connectReadsAPacket() throws Exception {
|
||||
// Socket host=mock(Socket.class);
|
||||
// InputStream stream = new ByteArrayInputStream(workingPacket);
|
||||
// when(host.getInputStream()).thenReturn(stream);
|
||||
// StreamReceiver streamReceiver = new StreamReceiver(host, pq);
|
||||
//
|
||||
// streamReceiver.connect();
|
||||
// assert pq.size() == 1;
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void connectDropsAMismatchedCrc() throws Exception {
|
||||
Socket host=mock(Socket.class);
|
||||
InputStream stream = new ByteArrayInputStream(crcMismatchPacket);
|
||||
when(host.getInputStream()).thenReturn(stream);
|
||||
StreamReceiver streamReceiver = new StreamReceiver(host, pq);
|
||||
|
||||
streamReceiver.connect();
|
||||
assert pq.size() == 0;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bytestoLongTest() {
|
||||
Socket host=mock(Socket.class);
|
||||
StreamReceiver streamReceiver = new StreamReceiver(host, pq);
|
||||
try {
|
||||
Class[] args = new Class[1];
|
||||
args[0] = byte[].class;
|
||||
Method bytesToLong = streamReceiver.getClass().getDeclaredMethod("bytesToLong", args);
|
||||
bytesToLong.setAccessible(true);
|
||||
byte[] sevenBtyeNumber = {0b01100100, 0b00110100, 0b00010100, 0b00000000, 0b00000000, 0b00000000, (byte)0b10000000};
|
||||
assert bytesToLong.invoke(streamReceiver, sevenBtyeNumber).equals(36028797020288100L);
|
||||
byte[] eightByteNumber = {0b01100100, 0b00110100, 0b00010100, 0b00000000, 0b00000000, 0b00000000, (byte)0b10000000, 0b00100101};
|
||||
assert bytesToLong.invoke(streamReceiver, eightByteNumber).equals(-1L);
|
||||
byte[] emptyArray = {};
|
||||
assert bytesToLong.invoke(streamReceiver, emptyArray).equals(0L);
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user