Hopefully final version of Hosting #story[1188]

main
Fan-Wu Yang 8 years ago
parent 9d1145b298
commit 928f5e31f0

@ -78,6 +78,18 @@
<version>0.7</version> <version>0.7</version>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
</dependencies> </dependencies>

@ -0,0 +1,50 @@
package shared.utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
/**
* Created by Gondr on 23/05/2017.
*/
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} catch (JSONException e) {
return null;
} finally {
is.close();
}
}
public static JSONArray readJsonFromUrlArray(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONArray json = new JSONArray(jsonText);
return json;
} finally {
is.close();
}
}
}

@ -10,6 +10,7 @@ import mock.app.Event;
import mock.exceptions.EventConstructionException; import mock.exceptions.EventConstructionException;
import visualiser.app.App; import visualiser.app.App;
import visualiser.app.MatchBrowserSingleton; import visualiser.app.MatchBrowserSingleton;
import visualiser.network.HttpMatchBrowserHost;
import visualiser.network.MatchBrowserInterface; import visualiser.network.MatchBrowserInterface;
import java.io.IOException; import java.io.IOException;
@ -64,8 +65,11 @@ public class HostGameController extends Controller {
try { try {
App.game = new Event(false, currentMapIndex); App.game = new Event(false, currentMapIndex);
App.gameType = currentMapIndex; App.gameType = currentMapIndex;
HttpMatchBrowserHost matchBrowserHost = new HttpMatchBrowserHost();
new Thread(matchBrowserHost).start();
connectSocket("localhost", 4942); connectSocket("localhost", 4942);
alertMatchBrowser(); //alertMatchBrowser();
} catch (EventConstructionException e) { } catch (EventConstructionException e) {
Logger.getGlobal().log(Level.SEVERE, "Could not create Event.", e); Logger.getGlobal().log(Level.SEVERE, "Could not create Event.", e);

@ -28,6 +28,7 @@ import visualiser.layout.View3D;
import visualiser.model.VisualiserBoat; import visualiser.model.VisualiserBoat;
import visualiser.model.VisualiserRaceEvent; import visualiser.model.VisualiserRaceEvent;
import visualiser.model.VisualiserRaceState; import visualiser.model.VisualiserRaceState;
import visualiser.network.HttpMatchBrowserHost;
import java.io.IOException; import java.io.IOException;
import java.net.Socket; import java.net.Socket;

@ -1,6 +1,7 @@
package visualiser.Controllers; package visualiser.Controllers;
import javafx.collections.FXCollections; import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList; import javafx.collections.ObservableList;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Button; import javafx.scene.control.Button;
@ -10,8 +11,12 @@ import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane; import javafx.scene.layout.AnchorPane;
import javafx.scene.media.AudioClip; import javafx.scene.media.AudioClip;
import network.Messages.HostGame; import network.Messages.HostGame;
import org.json.JSONArray;
import org.json.JSONObject;
import shared.utils.JsonReader;
import visualiser.app.MatchBrowserSingleton; import visualiser.app.MatchBrowserSingleton;
import visualiser.model.RaceConnection; import visualiser.model.RaceConnection;
import visualiser.network.HttpMatchBrowserClient;
import visualiser.network.MatchBrowserLobbyInterface; import visualiser.network.MatchBrowserLobbyInterface;
import java.io.IOException; import java.io.IOException;
@ -39,17 +44,17 @@ public class LobbyController extends Controller {
private AudioClip sound; private AudioClip sound;
//the socket for match browser //the socket for match browser
private DatagramSocket udpSocket; private HttpMatchBrowserClient httpMatchBrowserClient;
private MatchBrowserLobbyInterface matchBrowserLobbyInterface;
public void initialize() { public void initialize() {
httpMatchBrowserClient = new HttpMatchBrowserClient();
new Thread(httpMatchBrowserClient, "Match Client").start();
// set up the connection table // set up the connection table
connections = FXCollections.observableArrayList();
customConnections = FXCollections.observableArrayList(); customConnections = FXCollections.observableArrayList();
//connections.add(new RaceConnection("localhost", 4942, "Local Game")); //connections.add(new RaceConnection("localhost", 4942, "Local Game"));
lobbyTable.setItems(connections); lobbyTable.setItems(httpMatchBrowserClient.connections);
gameNameColumn.setCellValueFactory(cellData -> cellData.getValue().gamenameProperty()); gameNameColumn.setCellValueFactory(cellData -> cellData.getValue().gamenameProperty());
hostNameColumn.setCellValueFactory(cellData -> cellData.getValue().hostnameProperty()); hostNameColumn.setCellValueFactory(cellData -> cellData.getValue().hostnameProperty());
statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty()); statusColumn.setCellValueFactory(cellData -> cellData.getValue().statusProperty());
@ -63,7 +68,6 @@ public class LobbyController extends Controller {
}); });
joinGameBtn.setDisable(true); joinGameBtn.setDisable(true);
this.udpSocket = MatchBrowserSingleton.getInstance().getUdpSocket();
receiveMatchData(); receiveMatchData();
} }
@ -91,6 +95,7 @@ public class LobbyController extends Controller {
* @throws IOException socket error * @throws IOException socket error
*/ */
public void connectSocket() throws IOException { public void connectSocket() throws IOException {
httpMatchBrowserClient.interrupt();
RaceConnection connection = lobbyTable.getSelectionModel().getSelectedItem(); RaceConnection connection = lobbyTable.getSelectionModel().getSelectedItem();
Socket socket = new Socket(connection.getHostname(), connection.getPort()); Socket socket = new Socket(connection.getHostname(), connection.getPort());
InGameLobbyController iglc = (InGameLobbyController)loadScene("gameLobby.fxml"); InGameLobbyController iglc = (InGameLobbyController)loadScene("gameLobby.fxml");
@ -100,7 +105,7 @@ public class LobbyController extends Controller {
public void menuBtnPressed() throws IOException { public void menuBtnPressed() throws IOException {
sound = new AudioClip(this.getClass().getResource("/visualiser/sounds/buttonpress.wav").toExternalForm()); sound = new AudioClip(this.getClass().getResource("/visualiser/sounds/buttonpress.wav").toExternalForm());
sound.play(); sound.play();
matchBrowserLobbyInterface.closeSocket(); httpMatchBrowserClient.interrupt();
loadScene("title.fxml"); loadScene("title.fxml");
} }
@ -124,6 +129,7 @@ public class LobbyController extends Controller {
} }
public void receiveMatchData(){ public void receiveMatchData(){
/*
matchBrowserLobbyInterface = new MatchBrowserLobbyInterface(); matchBrowserLobbyInterface = new MatchBrowserLobbyInterface();
try { try {
matchBrowserLobbyInterface.startReceivingHostData(new DatagramSocket(4941)); matchBrowserLobbyInterface.startReceivingHostData(new DatagramSocket(4941));
@ -136,17 +142,25 @@ public class LobbyController extends Controller {
matchBrowserLobbyInterface.addObserver(o); matchBrowserLobbyInterface.addObserver(o);
} catch (SocketException e) { } catch (SocketException e) {
System.err.println("Socket 4941 in use"); System.err.println("Socket 4941 in use");
} }*/
} }
/** /**
* Adds the games received from the server * Adds the games received from the server
*/ */
private void addServerGames() { private void addServerGames() {
connections.clear(); httpMatchBrowserClient.connections.clear();
connections.addAll(customConnections); httpMatchBrowserClient.connections.addAll(customConnections);
httpMatchBrowserClient.connections.addListener(new ListChangeListener<RaceConnection>() {
@Override
public void onChanged(Change<? extends RaceConnection> c) {
refreshBtnPressed();
}
});
/*
for (HostGame game : matchBrowserLobbyInterface.getGames()) { for (HostGame game : matchBrowserLobbyInterface.getGames()) {
connections.add(new RaceConnection(game.getIp(), 4942, "Boat Game")); connections.add(new RaceConnection(game.getIp(), 4942, "Boat Game"));
} }*/
} }
} }

@ -8,6 +8,7 @@ import shared.dataInput.EmptyBoatDataSource;
import shared.dataInput.EmptyRaceDataSource; import shared.dataInput.EmptyRaceDataSource;
import shared.dataInput.EmptyRegattaDataSource; import shared.dataInput.EmptyRegattaDataSource;
import visualiser.gameController.ControllerClient; import visualiser.gameController.ControllerClient;
import visualiser.network.HttpMatchBrowserHost;
import visualiser.network.ServerConnection; import visualiser.network.ServerConnection;
import java.io.IOException; import java.io.IOException;
@ -115,5 +116,6 @@ public class VisualiserRaceEvent {
this.visualiserRaceServiceThread.interrupt(); this.visualiserRaceServiceThread.interrupt();
this.serverConnectionThread.interrupt(); this.serverConnectionThread.interrupt();
serverConnection.terminate(); serverConnection.terminate();
HttpMatchBrowserHost.httpMatchBrowserHost.interrupt();
} }
} }

@ -0,0 +1,38 @@
package visualiser.network;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.json.JSONArray;
import org.json.JSONObject;
import shared.utils.JsonReader;
import visualiser.model.RaceConnection;
import java.io.IOException;
/**
* Created by Gondr on 19/09/2017.
*/
public class HttpMatchBrowserClient extends Thread {
public ObservableList<RaceConnection> connections = FXCollections.observableArrayList();
@Override
public void run() {
while(!Thread.interrupted()) {
try {
JSONArray cons = JsonReader.readJsonFromUrlArray("http://api.umbrasheep.com/seng/get_matches/");
System.out.println("Got stuff");
System.out.println(cons.toString());
for (int i = 0; i < cons.length(); i++) {
JSONObject con = (JSONObject) cons.get(i);
connections.add(new RaceConnection((String) con.get("ip_address"), con.getInt("port"), "Boat Game"));
}
Thread.sleep(5000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

@ -0,0 +1,75 @@
package visualiser.network;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gondr on 19/09/2017.
*/
public class HttpMatchBrowserHost extends Thread {
private HttpClient httpClient;
private List<NameValuePair> params;
public static HttpMatchBrowserHost httpMatchBrowserHost = null;
public HttpMatchBrowserHost() throws IOException {
httpMatchBrowserHost = this;
httpClient = HttpClients.createDefault();
// Request parameters and other properties.
params = new ArrayList<>(2);
params.add(new BasicNameValuePair("port", "4942"));
params.add(new BasicNameValuePair("magic", "Thomas and Seng"));
sendHttp("http://api.umbrasheep.com/seng/registermatch/");
System.out.println("Register Match");
}
public void sendHttp(String domain) throws IOException {
HttpPost httppost = new HttpPost(domain);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
// do something useful
} finally {
instream.close();
}
} else {
throw new IOException("No Response from Host");
}
}
@Override
public void run() {
while(!Thread.interrupted()){
try {
sendHttp("http://api.umbrasheep.com/seng/keep_match_alive/");
System.out.println("Keep match ALive");
Thread.sleep(2000);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Loading…
Cancel
Save