multicast socket for score

This commit is contained in:
Lorenzo Iovino 2017-06-27 15:45:28 +02:00
parent 5f8fe0ae2d
commit f7c9d0ff99
21 changed files with 1621 additions and 589 deletions

View file

@ -1,11 +1,16 @@
package com.texttwist.server.components;
import com.texttwist.client.App;
import com.texttwist.server.models.Match;
import com.texttwist.server.tasks.*;
import constants.Config;
import models.Message;
import javax.swing.*;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
@ -61,36 +66,21 @@ public class ThreadProxy implements Callable<Boolean> {
if(!joinMatchRes){
//NON FARE NULLA, ASPETTA GLI ALTRI
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<String>());
byteMessage = new String(message.toString()).getBytes();
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
Future<Boolean> matchTimeout = threadPool.submit(new MatchTimeout(match));
Boolean matchTimeoutRes = matchTimeout.get();
if(matchTimeoutRes){
} else {
//TODO If game is started not send this message
if(!match.isStarted()) {
for (int i = 0; i < match.playersSocket.size(); i++) {
socketChannel = match.playersSocket.get(i).getValue();
if (socketChannel != null) {
buffer.clear();
message = new Message("TIMEOUT", "", "", new DefaultListModel<>());
byteMessage = new String(message.toString()).getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
//clientSocket.close();
}
}
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
Boolean joinTimeoutRes = joinTimeout.get();
if(!joinTimeoutRes){
Future<Boolean> sendMessageJoinTimeout = threadPool.submit(
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
if(!sendMessageJoinTimeoutRes){
return sendMessageJoinTimeoutRes;
}
}
return matchTimeoutRes;
}
} else {
@ -124,25 +114,23 @@ public class ThreadProxy implements Callable<Boolean> {
try {
Boolean joinMatchRes = joinMatch.get();
if(joinMatchRes){
System.out.print("START THE FUCKING GAME!!!!");
//Find the game, send broadcast communication
// buffer.flip();
System.out.print("START THE GAME!!!!");
Match match = Match.findMatch(request.data.get(0));
Future<DefaultListModel<String>> generateWords = threadPool.submit(new GenerateWords());
Future<DefaultListModel<String>> generateWords = threadPool.submit(new GenerateLetters());
match.setLetters(generateWords.get());
match.letters.addElement(String.valueOf(match.multicastId));
for (int i =0; i< match.playersSocket.size(); i++) {
System.out.println("INVIO");
socketChannel = match.playersSocket.get(i).getValue();
if(socketChannel!=null) {
if(socketChannel != null) {
buffer.clear();
Message message = new Message("GAME_STARTED", "", "", match.letters);
match.startGame();
byteMessage = new String(message.toString()).getBytes();
byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
try {
@ -154,6 +142,29 @@ public class ThreadProxy implements Callable<Boolean> {
}
}
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match));
Boolean receiveWordsRes = receiveWords.get();
if(!receiveWordsRes){
match.setUndefinedScorePlayersToZero();
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");
}
System.out.println(match.playersScore);
Message msg = new Message("FINALSCORE","SERVER","", match.getMatchPlayersScoreAsStringList());
MulticastSocket s = new MulticastSocket(4000);
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(),
ia, 4000);
s.send(hi);
//RISPONDI CON LA CLASSIFICA
//TODO
return receiveWordsRes;
//ULTIMO A JOINARE! INIZIA GIOCO
} else {
System.out.print("WAIT FRIENDS");
@ -163,7 +174,10 @@ public class ThreadProxy implements Callable<Boolean> {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} {
} catch (IOException e) {
e.printStackTrace();
}
{
}
default:

View file

@ -16,7 +16,7 @@ import java.util.stream.Stream;
*/
public class Dictionary {
DefaultListModel<String> wordList = new DefaultListModel<>();
static DefaultListModel<String> wordList = new DefaultListModel<>();
private Random randomGenerator;
public Dictionary(String dictionaryPath) {
@ -55,4 +55,13 @@ public class Dictionary {
}
}
public static Boolean isContainedInDictionary(String word){
for(int i = 0; i< wordList.size(); i++){
if(wordList.get(i).equals(word)) {
return true;
}
}
return false;
}
}

View file

@ -17,15 +17,17 @@ public class Match {
public DefaultListModel<Pair<String,SocketChannel>> playersSocket = new DefaultListModel<Pair<String, SocketChannel>>();
private boolean started = false;
public String matchCreator;
public Integer multicastId;
public DefaultListModel<String> letters;
public DefaultListModel<Pair<String,Integer>> playersScore = new DefaultListModel<Pair<String, Integer>>();
public Match(String matchCreator, DefaultListModel<String> players){
for (int i =0; i < players.size(); i++){
this.playersStatus.addElement(new Pair<>(players.get(i), 0));
this.playersScore.addElement(new Pair<>(players.get(i), -1));
this.playersSocket.addElement(new Pair<>(players.get(i), null));
}
this.multicastId = this.generateMulticastId();
this.matchCreator = matchCreator;
}
@ -45,9 +47,49 @@ public class Match {
public void startGame(){
this.started=true;
}
public void setScore(String player, Integer score){
for(int i = 0; i<playersScore.size(); i++) {
if (playersScore.get(i).getKey().equals(player)) {
playersScore.set(i, new Pair<String, Integer>(player, score));
}
}
}
public Boolean allPlayersSendedHisScore(){
for(int i = 0; i<playersScore.size(); i++) {
if (playersScore.get(i).getValue() == -1) {
return false;
}
}
return true;
}
public void setUndefinedScorePlayersToZero(){
for(int i = 0; i<playersScore.size(); i++) {
if (playersScore.get(i).getValue() == -1) {
playersScore.set(i, new Pair<String, Integer>(playersScore.get(i).getKey(), 0));
}
}
}
public DefaultListModel<String> getMatchPlayersScoreAsStringList(){
DefaultListModel<String> l = new DefaultListModel<>();
for(int i = 0; i<playersScore.size(); i++) {
l.addElement(playersScore.get(i).getKey()+":"+playersScore.get(i).getValue());
}
return l;
}
private int generateMulticastId(){
if(activeMatches.size() != 0) {
return activeMatches.lastElement().multicastId+1;
} else {
return 4000;
}
}
public void setLetters(DefaultListModel<String> letters){
this.letters = letters;
}

View file

@ -0,0 +1,52 @@
package com.texttwist.server.tasks;
import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match;
import javax.swing.*;
import java.util.concurrent.Callable;
/**
* Created by loke on 27/06/2017.
*/
public class ComputeScore implements Callable<Integer> {
public DefaultListModel<String> words;
public String sender;
public Match match;
public ComputeScore(String sender, Match match, DefaultListModel<String> words){
this.words = words;
this.sender = sender;
this.match = match;
}
@Override
public Integer call() throws Exception {
System.out.println("SET SCORE");
Integer score = 0;
for(int i = 0; i< words.size(); i++){
if(isValid(words.get(i), match.letters)){
score += words.get(i).length();
}
}
match.setScore(sender, score);
return score;
}
private Boolean isValid(String word, DefaultListModel<String> letters) {
for ( int i =0 ; i< word.length(); i++){
String c = Character.toString(word.charAt(i));
Boolean isCharacterPresent = false;
for(int j =0 ; j< letters.size(); j++){
if(c.equals(letters.get(j))){
isCharacterPresent = true;
}
}
if(!isCharacterPresent){
return false;
}
}
return Dictionary.isContainedInDictionary(word);
}
}

View file

@ -12,10 +12,10 @@ import java.util.concurrent.Callable;
/**
* Created by loke on 25/06/2017.
*/
public class GenerateWords implements Callable<DefaultListModel<String>> {
public class GenerateLetters implements Callable<DefaultListModel<String>> {
public GenerateWords(){
public GenerateLetters(){
}
@ -24,7 +24,6 @@ public class GenerateWords implements Callable<DefaultListModel<String>> {
DefaultListModel<String> l = new DefaultListModel<String>();
String word = GameServer.dict.getRandomWord(6, 7);
System.out.println(word);
for (int i = 0;i < word.length(); i++){
l.addElement(String.valueOf(word.charAt(i)));
}

View file

@ -0,0 +1,36 @@
package com.texttwist.server.tasks;
import com.texttwist.client.App;
import com.texttwist.server.models.Match;
import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
/**
* Created by loke on 23/06/2017.
*/
public class JoinTimeout implements Callable<Boolean> {
public Match match;
public JoinTimeout(Match match) {
this.match = match;
System.out.println("Math started, countdown for join!");
}
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(7*60*1000);
System.out.println("TIMEOUT - MANDA MESSAGGIO ERRORE A TUTTI GLI UTENTI DEL MATCH");
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
}
}

View file

@ -1,39 +1,36 @@
package com.texttwist.server.tasks;
import com.texttwist.client.App;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.texttwist.server.models.Match;
import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
import java.util.concurrent.Callable;
/**
* Created by loke on 23/06/2017.
* Created by loke on 27/06/2017.
*/
public class MatchTimeout implements Callable<Boolean> {
public Match match;
Boolean receiveWords;
public MatchTimeout(Match match) {
this.match = match;
System.out.println("Math started, countdown for join!");
public MatchTimeout(Boolean receiveWords) {
this.receiveWords = receiveWords;
System.out.println("Match started, countdown for end words!");
}
@Override
public Boolean call() throws Exception {
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
Thread.currentThread().sleep(7*60*1000);
System.out.println("TIMEOUT - MANDA MESSAGGIO ERRORE A TUTTI GLI UTENTI DEL MATCH");
return false;
Thread.currentThread().sleep(3*60*1000); //TODO 5*60*1000
System.out.println("timer scaduto");
receiveWords = false;
System.out.println("TIMEOUT - SETTA A 0 il punteggio degli utenti che non hanno inviato le parole");
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
return false;
return true;
}
}

View file

@ -0,0 +1,60 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
import javax.swing.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by loke on 27/06/2017.
*/
public class ReceiveWords implements Callable<Boolean>{
protected ExecutorService threadPool = Executors.newCachedThreadPool();
public Boolean receiveWords = true;
public Match match;
public ReceiveWords(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
System.out.print("READY TO Receive words !!!!");
DatagramSocket serverSocket = new DatagramSocket(Config.WordsReceiverServerPort);
byte[] receiveData = new byte[1024];
Future<Boolean> matchTimeout = threadPool.submit(new MatchTimeout(receiveWords));
while(receiveWords)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String rcv = new String( receivePacket.getData());
System.out.println("RECEIVED: " + rcv);
Message msg = Message.toMessage(rcv);
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();
System.out.println(match.allPlayersSendedHisScore());
if(match.allPlayersSendedHisScore()){
//matchTimeout.cancel(true);
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,47 @@
package com.texttwist.server.tasks;
import com.texttwist.server.models.Match;
import models.Message;
import javax.swing.*;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
/**
* Created by loke on 27/06/2017.
*/
public class SendMessageToAllPlayers implements Callable<Boolean> {
public Match match;
public Message message;
public SocketChannel socketChannel;
public SendMessageToAllPlayers(Match match, Message message, SocketChannel socketChannel){
this.match = match;
this.message = message;
this.socketChannel = socketChannel;
}
@Override
public Boolean call() throws Exception {
ByteBuffer buffer = ByteBuffer.allocate(1024);
if(!match.isStarted()) {
for (int i = 0; i < match.playersSocket.size(); i++) {
socketChannel = match.playersSocket.get(i).getValue();
if (socketChannel != null) {
buffer.clear();
byte[] byteMessage = message.toString().getBytes();
buffer = ByteBuffer.wrap(byteMessage);
socketChannel.write(buffer);
//clientSocket.close();
System.out.println("SEND TO ALL" + message.toString());
return false;
}
}
}
return true;
}
}