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.

91 lines
3.5 KiB

package networkInterface;
import model.ClientAdress;
import model.MatchTable;
import model.TableKey;
import network.BinaryMessageDecoder;
import network.Exceptions.InvalidMessageException;
import network.MessageDecoders.HostGameMessageDecoder;
import network.MessageDecoders.HostedGamesRequestDecoder;
import network.Messages.HostGame;
import network.Messages.HostGamesRequest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.*;
/**
* Holds the output for the network for
*/
public class NetworkInterface {
private DatagramSocket serverSocket;
private byte[] receiveData = new byte[1024];
private byte[] sendData = new byte[1024];
private Set<ClientAdress> clientsAddresses;
private MatchTable matchTable;
public NetworkInterface(){
this.clientsAddresses = new HashSet<ClientAdress>();
this.matchTable = new MatchTable();
try {
this.serverSocket = new DatagramSocket(3779);
this.run();
} catch (IOException e) {
System.err.println("Error listening on port: " + this.serverSocket.getLocalPort() + ".");
System.exit(-1);
}
}
private void run() throws IOException{
while(true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
BinaryMessageDecoder messageDecoder = new BinaryMessageDecoder(receivePacket.getData());
switch (messageDecoder.getHeaderMessageType()){
case 108:
//decode and update table
HostGameMessageDecoder decoder = new HostGameMessageDecoder();
HostGame newKnownGame;
try{
newKnownGame = (HostGame) decoder.decode(messageDecoder.getMessageBody());
this.matchTable.addEntry(receivePacket.getAddress().getHostAddress(), receivePacket.getPort(), newKnownGame);
System.out.println(matchTable);
}catch (InvalidMessageException e){
System.out.println(e);
System.err.println("Message received that is not a hostedGame packet");
}
break;
case 109:
//update known clients
HostedGamesRequestDecoder decoder2 = new HostedGamesRequestDecoder();
HostGamesRequest newKnownGames;
try{
newKnownGames = (HostGamesRequest) decoder2.decode(messageDecoder.getMessageBody());
if (newKnownGames.getKnownGames().size() == 0){
//this is just an alert message with no content
clientsAddresses.add(new ClientAdress(receivePacket.getAddress().getHostAddress(), receivePacket.getPort()));
}
System.out.println("Clients: " + clientsAddresses);
}catch (InvalidMessageException e){
System.out.println(e);
System.err.println("Message received that is not a hostedGamesRequest packet");
}
break;
}
//client ip and port
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
}
}
}