SUPER DUPER HYPER!!!

This commit is contained in:
Lorenzo Iovino 2017-07-09 16:45:46 +02:00
parent 3a528f307b
commit cb63402b9f
12 changed files with 2741 additions and 494 deletions

View file

@ -2,6 +2,7 @@
package com.texttwist.server.components;
import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.ReceiveWords;
import constants.Config;
import models.Message;
import utilities.Logger;
@ -25,12 +26,14 @@ public class GameServer implements Runnable{
private int serverPort;
private ThreadProxy proxy;
private ReceiveWords wordsReceiver;
private DatagramChannel datagramChannel;
private Selector selector = null;
private ExecutorService threadPool = Executors.newCachedThreadPool();
private String dictionaryPath = "./Server/resources/dictionary";
public static Dictionary dict;
ByteBuffer bufferWords = ByteBuffer.allocate(1024);
public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
@ -50,10 +53,13 @@ public class GameServer implements Runnable{
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(serverPort));
serverSocketChannel.register(selector, OP_ACCEPT);
InetSocketAddress address = new InetSocketAddress(Config.WordsReceiverServerPort);
InetSocketAddress address = new InetSocketAddress(Config.WordsReceiverServerURI,Config.WordsReceiverServerPort);
datagramChannel = DatagramChannel.open();
DatagramSocket datagramSocket = datagramChannel.socket();
datagramSocket.bind(address);
datagramChannel.configureBlocking(true);
datagramChannel.connect(address);
wordsReceiver = new ReceiveWords(datagramChannel, bufferWords);
threadPool.submit(wordsReceiver);
Logger.write("GamePage Service is running at "+this.serverPort+" port...");
} catch (IOException e) {
@ -91,8 +97,7 @@ public class GameServer implements Runnable{
if (line.startsWith("MESSAGE")) {
SessionsManager.getInstance().printAll();
Message msg = Message.toMessage(line);
ByteBuffer bufferWords = ByteBuffer.allocate(1024);
proxy = new ThreadProxy(msg, client, datagramChannel, bufferWords);
proxy = new ThreadProxy(msg, client, bufferMessages);
threadPool.submit(proxy);
}

View file

@ -1,5 +1,6 @@
package com.texttwist.server.components;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.*;
import constants.Config;
@ -26,16 +27,15 @@ public class ThreadProxy implements Callable<Boolean> {
protected final ExecutorService threadPool = Executors.newCachedThreadPool();
private final Message request;
private final SocketChannel socketChannel;
private final DatagramChannel datagramChannel;
private ByteBuffer buffer;
private ByteBuffer bufferMessage;
boolean matchNotAvailable =false;
ThreadProxy(Message request, SocketChannel socketChannel, DatagramChannel datagramChannel, ByteBuffer buffer){
ThreadProxy(Message request, SocketChannel socketChannel, ByteBuffer bufferMessage) {
this.request = request;
this.socketChannel = socketChannel;
this.datagramChannel = datagramChannel;
this.buffer = buffer;
this.bufferMessage = bufferMessage;
}
@ -45,7 +45,7 @@ public class ThreadProxy implements Callable<Boolean> {
@Override
public Boolean call() {
ByteBuffer buffer = ByteBuffer.allocate(1024);
bufferMessage = ByteBuffer.allocate(1024);
byte[] byteMessage = null;
if(isValidToken(request.token)){
switch(request.message){
@ -76,13 +76,14 @@ public class ThreadProxy implements Callable<Boolean> {
//NON FARE NULLA, ASPETTA GLI ALTRI
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<String>());
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
bufferMessage = ByteBuffer.wrap(byteMessage);
socketChannel.write(bufferMessage);
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
Boolean joinTimeoutRes = joinTimeout.get();
if(!joinTimeoutRes){
match.timeout = joinTimeout;
joinTimeout.get();
if(match.joinTimeout){
Future<Boolean> sendMessageJoinTimeout = threadPool.submit(
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
@ -90,6 +91,8 @@ public class ThreadProxy implements Callable<Boolean> {
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
return sendMessageJoinTimeoutRes;
}
} else {
System.out.println("TIMEOUT FINITO SENZA EFFETTI");
}
}
@ -105,9 +108,9 @@ public class ThreadProxy implements Callable<Boolean> {
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<String>());
byteMessage = new String(message.toString()).getBytes();
buffer.clear();
buffer = ByteBuffer.wrap(byteMessage);
this.socketChannel.write(buffer);
bufferMessage.clear();
bufferMessage = ByteBuffer.wrap(byteMessage);
this.socketChannel.write(bufferMessage);
break;
}
} catch (InterruptedException e) {
@ -125,9 +128,9 @@ public class ThreadProxy implements Callable<Boolean> {
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
socketChannel.write(buffer);
socketChannel.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
}
@ -145,7 +148,7 @@ public class ThreadProxy implements Callable<Boolean> {
Boolean joinMatchRes = joinMatch.get();
if(joinMatchRes){
if(match.joinTimeout == false) {
if(!match.joinTimeout) {
Future<DefaultListModel<String>> generateLetters = threadPool.submit(new GenerateLetters());
match.setLetters(generateLetters.get());
match.letters.addElement(String.valueOf(match.multicastId));
@ -153,47 +156,24 @@ public class ThreadProxy implements Callable<Boolean> {
for (int i = 0; i < match.playersSocket.size(); i++) {
SocketChannel socketClient = match.playersSocket.get(i).getValue();
if (socketClient != null) {
buffer.clear();
bufferMessage.clear();
Message message = new Message("GAME_STARTED", "", "", match.letters);
match.startGame();
match.timeout.cancel(true);
System.out.println("TIMEOUT CANCELLEd");
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
socketClient.write(buffer);
socketClient.write(bufferMessage);
} catch (IOException e) {
}
//clientSocket.close();
}
}
if (!matchNotAvailable) {
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match, datagramChannel, buffer));
Boolean receiveWordsRes = receiveWords.get();
if (receiveWordsRes) {
System.out.println("ZERO PUNTI a chi non ha ancora inviato le lettere, TIMER SCADUTO");
} else {
System.out.println("TUTTI I GIOCATORI HANNO CONSEGNATO IN TEMPO");
}
match.setUndefinedScorePlayersToZero();
while (true) {
Message msg = new Message("FINALSCORE", "SERVER", "", match.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = new MulticastSocket(match.multicastId);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
multicastSocket.send(hi);
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
//multicastSocket.disconnect();
//multicastSocket.close();
}
} else {
if (matchNotAvailable) {
return false;
}
}
@ -202,13 +182,13 @@ public class ThreadProxy implements Callable<Boolean> {
//ULTIMO A JOINARE! INIZIA GIOCO
} else {
if(match == null){
buffer = ByteBuffer.allocate(1024);
bufferMessage = ByteBuffer.allocate(1024);
if (socketChannel != null) {
Message msg = new Message("MATCH_NOT_AVAILABLE", "", null, new DefaultListModel<>());
buffer.clear();
bufferMessage.clear();
byteMessage = msg.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
bufferMessage = ByteBuffer.wrap(byteMessage);
socketChannel.write(bufferMessage);
matchNotAvailable = true;
}
//Match non disponibile

View file

@ -1,6 +1,7 @@
package com.texttwist.server.models;
import com.texttwist.server.components.GameServer;
import com.texttwist.server.tasks.MatchTimeout;
import constants.Config;
import javafx.util.Pair;
@ -9,6 +10,10 @@ import java.net.DatagramSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static com.texttwist.server.components.GameServer.activeMatches;
@ -21,8 +26,12 @@ public class Match {
private boolean started = false;
public final String matchCreator;
public Integer multicastId;
public Future<Boolean> timeout;
public Future<Boolean> matchTimeout;
public boolean joinTimeout =true;
public DefaultListModel<String> letters;
protected ExecutorService threadPool = Executors.newSingleThreadExecutor();
public final List<Pair<String,Integer>> playersScore = Collections.synchronizedList(new ArrayList<>());
public Match(String matchCreator, DefaultListModel<String> players){
@ -38,16 +47,17 @@ public class Match {
}
public static Match findMatch(List<Match> matches, String matchName){
for (int i = 0; i < matches.size(); i++) {
if (matches.get(i).matchCreator.equals(matchName)) {
return matches.get(i);
synchronized (matches) {
for (int i = 0; i < matches.size(); i++) {
if (matches.get(i).matchCreator.equals(matchName)) {
return matches.get(i);
}
}
return null;
}
return null;
}
public void printAll(){
for (int i = 0; i < playersScore.size(); i++) {
System.out.println(playersScore.get(i).getKey() + " : " +playersScore.get(i).getValue());
@ -67,9 +77,9 @@ public class Match {
return started;
}
public Match findMatchByPlayer(String player){
public static Match findMatchByPlayer(String player){
for (int i = 0; i < activeMatches.size(); i++) {
for (int j = 0; j < playersStatus.size(); j++) {
for (int j = 0; j < activeMatches.get(i).playersStatus.size(); j++) {
if (activeMatches.get(i).playersStatus.get(j).getKey().equals(player)) {
return activeMatches.get(i);
}
@ -83,20 +93,25 @@ public class Match {
public void startGame(){
this.started=true;
this.matchTimeout = threadPool.submit(new MatchTimeout());
}
public void setScore(String player, Integer score){
final Match m = findMatchByPlayer(player);
m.printAll();
Match m = findMatchByPlayer(player);
synchronized (m) {
m.printAll();
for (int i = 0; i < m.playersScore.size(); i++) {
if (m.playersScore.get(i).getKey().equals(player)) {
m.playersScore.set(i, new Pair<String, Integer>(player, score));
}
}
}
}
public Boolean allPlayersSendedHisScore(){
System.out.println(matchCreator);
printAll();
for (int i = 0; i < playersScore.size(); i++) {
if (playersScore.get(i).getValue() == -1) {

View file

@ -3,11 +3,18 @@ import com.texttwist.client.App;
import com.texttwist.server.components.AccountsManager;
import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
import models.User;
import javax.swing.*;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.Callable;
import static com.texttwist.server.components.GameServer.activeMatches;
/**
* Created by loke on 27/06/2017.
*/
@ -15,26 +22,62 @@ public class ComputeScore implements Callable<Integer> {
public DefaultListModel<String> words;
public final String sender;
public final Match match;
public Match match;
public ComputeScore(String sender, Match match, DefaultListModel<String> words){
public ComputeScore(String sender, DefaultListModel<String> words, Match match){
this.words = words;
this.sender = sender;
this.match = match;
this.sender = sender;
}
@Override
public Integer call() throws Exception {
System.out.println("COMPUTE SCORE STARTED");
System.out.println(match);
System.out.println("COMPUTE SCORE STAsssssRTED");
synchronized (match) {
System.out.print("CALCOLO LO SCORE PER " + match.matchCreator);
Integer score = 0;
for (int i = 0; i < words.size(); i++) {
if (isValid(words.get(i), match.letters)) {
score += words.get(i).length();
}
}
System.out.println("SOODDISDIS");
match.setScore(sender, score);
User u = AccountsManager.getInstance().findUser(sender);
u.addScore(score);
if(match.allPlayersSendedHisScore()) {
match.matchTimeout.cancel(true);
//channel.close();
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
match.setUndefinedScorePlayersToZero();
System.out.println("SEND BROADCAST");
while (true) {
System.out.println("SENDING");
Message msg = new Message("FINALSCORE", "SERVER", "", match.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = new MulticastSocket(match.multicastId);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
multicastSocket.send(hi);
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
//multicastSocket.disconnect();
//multicastSocket.close();
}
}
return score;
}
}
private Boolean isValid(String word, DefaultListModel<String> letters) {

View file

@ -17,7 +17,8 @@ public class JoinTimeout implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(1*5*1000);
Thread.currentThread().sleep(1*20*1000);
System.out.println("TIMEOUTTTT");
if(match.joinTimeout) {
return false;

View file

@ -8,17 +8,20 @@ import models.Message;
import javax.swing.*;
import javax.xml.crypto.Data;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static com.texttwist.server.components.GameServer.activeMatches;
/**
* Created by loke on 27/06/2017.
*/
@ -26,53 +29,42 @@ public class ReceiveWords implements Callable<Boolean>{
protected ExecutorService threadPool = Executors.newCachedThreadPool();
public DatagramChannel DatagramChannel;
public final Match match;
byte[] receiveData = new byte[1024];
public DatagramChannel channel;
ByteBuffer buffer;
public ReceiveWords(Match match, DatagramChannel DatagramChannel, ByteBuffer buffer) {
this.match = match;
public ReceiveWords(DatagramChannel channel, ByteBuffer buffer) {
this.buffer = buffer;
this.DatagramChannel = DatagramChannel;
this.channel = channel;
}
@Override
public Boolean call() throws Exception {
Future<Boolean> matchTimeout = threadPool.submit(new MatchTimeout());
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
Message msg;
DatagramSocket s = new DatagramSocket(Config.WordsReceiverServerPort);
while(true) {
DatagramChannel.receive(buffer);
buffer.flip();
int limits = buffer.limit();
byte bytes[] = new byte[limits];
buffer.get(bytes, 0, limits);
String rcv = new String(bytes);
byte[] buf = new byte[1024];
System.out.println("RECEIVIN WORDS");
buffer.rewind();
msg = Message.toMessage(rcv);
if(msg.message.equals("WORDS")){
break;
DatagramPacket packet = new DatagramPacket(buf, buf.length);
s.receive(packet);
System.out.println("WORDS RECEIVED");
String rcv = new String(packet.getData());
System.out.println(rcv);
if (rcv.startsWith("MESSAGE")) {
msg = Message.toMessage(rcv);
System.out.println(msg.sender);
Match match = Match.findMatchByPlayer(msg.sender);
threadPool.submit(new ComputeScore(msg.sender, msg.data, match));
}
}
Future<Integer> computeScore = threadPool.submit(new ComputeScore(msg.sender, match, msg.data));
//Se tutti hanno inviato le parole, blocca il timer e restituisci true
computeScore.get();
if(match.allPlayersSendedHisScore()){
match.setUndefinedScorePlayersToZero();
matchTimeout.cancel(true);
DatagramChannel.close();
return true;
}
return false;
}