up funzionante perfetto

This commit is contained in:
Lorenzo Iovino 2017-07-10 21:34:37 +02:00
parent cb63402b9f
commit 6b915932ae
20 changed files with 2541 additions and 576 deletions

View file

@ -39,7 +39,6 @@ public class AccountsManager {
}
public boolean exists(String userName) {
synchronized(users) {
Iterator<User> i = users.iterator();
while (i.hasNext()) {
if (i.next().userName.equals(userName)) {
@ -47,11 +46,10 @@ public class AccountsManager {
}
}
return false;
}
}
public boolean checkPassword(String userName, String password) {
synchronized(users) {
Iterator<User> i = users.iterator();
while (i.hasNext()) {
User account = i.next();
@ -60,11 +58,10 @@ public class AccountsManager {
}
}
return false;
}
}
public User findUser(String userName){
synchronized(users) {
Iterator<User> i = users.iterator();
while (i.hasNext()) {
User u = i.next();
@ -73,7 +70,7 @@ public class AccountsManager {
}
}
return null;
}
}
public int size(){

View file

@ -17,7 +17,6 @@ import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static java.nio.channels.SelectionKey.OP_ACCEPT;
import static java.nio.channels.SelectionKey.OP_READ;
@ -57,16 +56,17 @@ public class GameServer implements Runnable{
datagramChannel = DatagramChannel.open();
datagramChannel.configureBlocking(true);
datagramChannel.connect(address);
Logger.write("GamePage Service is running at "+this.serverPort+" port...");
wordsReceiver = new ReceiveWords(datagramChannel, bufferWords);
threadPool.submit(wordsReceiver);
Logger.write("GamePage Service is running at "+this.serverPort+" port...");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
System.out.println("WAITING FOR MSG");
try {
selector.select();
} catch (IOException e) {
@ -76,6 +76,7 @@ public class GameServer implements Runnable{
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
ByteBuffer bufferMessages = ByteBuffer.allocate(1024);
bufferMessages.clear();
SocketChannel client = null;
SelectionKey key = iter.next();
iter.remove();
@ -93,7 +94,7 @@ public class GameServer implements Runnable{
if (client.read(bufferMessages) != -1) {
bufferMessages.flip();
String line = new String(bufferMessages.array(), bufferMessages.position(), bufferMessages.remaining());
System.out.println(line);
if (line.startsWith("MESSAGE")) {
SessionsManager.getInstance().printAll();
Message msg = Message.toMessage(line);

View file

@ -29,11 +29,12 @@ public class NotificationServer implements INotificationServer {
}
public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException {
if(clients.remove(client)) {
if (clients.remove(client)) {
System.out.println("Client unregistered");
} else {
System.out.println("Unable to unregister client");
}
}
public synchronized void sendInvitations(String username, DefaultListModel<String> users){
@ -43,14 +44,14 @@ public class NotificationServer implements INotificationServer {
while (i.hasNext()) {
client = (INotificationClient) i.next();
try {
System.out.println("SENDING INVITE TO "+users);
client.sendInvite(username, users);
} catch (RemoteException e) {
try {
unregisterForCallback(client);
} catch (RemoteException e1) {
e1.printStackTrace();
}
System.out.println("Sembra down");
//unregisterForCallback(client);
}
}
}
}

View file

@ -30,13 +30,12 @@ public class SessionsManager {
}
public void printAll(){
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
Session elem = i.next();
System.out.println(elem.account.userName + " | " + elem.token);
}
}
}
public boolean remove(String userName){
@ -51,7 +50,6 @@ public class SessionsManager {
}
public Session getSession(String userName) {
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
Session elem = i.next();
@ -60,11 +58,10 @@ public class SessionsManager {
}
}
return null;
}
}
public boolean exists(String userName) {
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
Session elem = i.next();
@ -73,12 +70,11 @@ public class SessionsManager {
}
}
return false;
}
}
public boolean isValidToken(String token) {
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
if (i.next().token.equals(token)) {
@ -86,7 +82,7 @@ public class SessionsManager {
}
}
return false;
}
}
}

View file

@ -73,27 +73,28 @@ public class ThreadProxy implements Callable<Boolean> {
Boolean joinMatchRes = joinMatch.get();
if(!joinMatchRes){
bufferMessage = ByteBuffer.allocate(1024);
//NON FARE NULLA, ASPETTA GLI ALTRI
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<String>());
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<>());
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
socketChannel.write(bufferMessage);
}
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
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();
if(!sendMessageJoinTimeoutRes){
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
return sendMessageJoinTimeoutRes;
}
} else {
System.out.println("TIMEOUT FINITO SENZA EFFETTI");
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
joinTimeout.get();
if(match.joinTimeout){
Future<Boolean> sendMessageJoinTimeout = threadPool.submit(
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
if(!sendMessageJoinTimeoutRes){
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
return sendMessageJoinTimeoutRes;
}
} else {
System.out.println("TIMEOUT FINITO SENZA EFFETTI");
return true;
}
} else {
@ -106,12 +107,12 @@ public class ThreadProxy implements Callable<Boolean> {
}
} else {
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<String>());
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<>());
byteMessage = new String(message.toString()).getBytes();
bufferMessage.clear();
bufferMessage = ByteBuffer.wrap(byteMessage);
this.socketChannel.write(bufferMessage);
break;
return false;
}
} catch (InterruptedException e) {
e.printStackTrace();
@ -125,16 +126,22 @@ public class ThreadProxy implements Callable<Boolean> {
Future<DefaultListModel<String>> computeHighscores = threadPool.submit(new ComputeHighscores());
try {
DefaultListModel<String> computeHighscoresRes = computeHighscores.get();
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
byteMessage = message.toString().getBytes();
bufferMessage.clear();
bufferMessage = ByteBuffer.allocate(1024);
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
socketChannel.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
}
break;
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining());
System.out.println("INVIO HIGHSCORES "+ s);
socketChannel.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
}
return false;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
@ -157,33 +164,35 @@ public class ThreadProxy implements Callable<Boolean> {
SocketChannel socketClient = match.playersSocket.get(i).getValue();
if (socketClient != null) {
bufferMessage.clear();
bufferMessage = ByteBuffer.allocate(1024);
Message message = new Message("GAME_STARTED", "", "", match.letters);
match.startGame();
match.timeout.cancel(true);
System.out.println("TIMEOUT CANCELLEd");
byteMessage = message.toString().getBytes();
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining());
System.out.println("INVIO GAME_STARTED "+ s);
socketClient.write(bufferMessage);
} catch (IOException e) {
}
//clientSocket.close();
}
}
if (matchNotAvailable) {
return false;
}
}
//RISPONDI CON LA CLASSIFICA
// break;
//ULTIMO A JOINARE! INIZIA GIOCO
} else {
if(match == null){
bufferMessage = ByteBuffer.allocate(1024);
if (socketChannel != null) {
bufferMessage = ByteBuffer.allocate(1024);
Message msg = new Message("MATCH_NOT_AVAILABLE", "", null, new DefaultListModel<>());
bufferMessage.clear();
byteMessage = msg.toString().getBytes();

View file

@ -4,10 +4,11 @@ import com.texttwist.server.components.GameServer;
import com.texttwist.server.tasks.MatchTimeout;
import constants.Config;
import javafx.util.Pair;
import models.Message;
import javax.swing.*;
import java.net.DatagramSocket;
import java.net.Socket;
import java.io.IOException;
import java.net.*;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.Callable;
@ -27,7 +28,7 @@ public class Match {
public final String matchCreator;
public Integer multicastId;
public Future<Boolean> timeout;
public Future<Boolean> matchTimeout;
public boolean matchTimeout = true;
public boolean joinTimeout =true;
public DefaultListModel<String> letters;
protected ExecutorService threadPool = Executors.newSingleThreadExecutor();
@ -46,15 +47,31 @@ public class Match {
}
public static Match findMatch(List<Match> matches, String matchName){
synchronized (matches) {
for (int i = 0; i < matches.size(); i++) {
if (matches.get(i).matchCreator.equals(matchName)) {
return matches.get(i);
}
public Void sendScores(){
while (true) {
System.out.println("SENDING");
Message msg = new Message("FINALSCORE", "SERVER", "", this.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = null;
try {
multicastSocket = new MulticastSocket(this.multicastId);
InetAddress ia = null;
ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, this.multicastId);
multicastSocket.send(hi);
} catch (IOException e) {
e.printStackTrace();
}
return null;
activeMatches.remove(Match.findMatchIndex(activeMatches, this.matchCreator));
}
}
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);
}
}
return null;
}
@ -93,19 +110,17 @@ public class Match {
public void startGame(){
this.started=true;
this.matchTimeout = threadPool.submit(new MatchTimeout());
threadPool.submit(new MatchTimeout(this));
}
public void setScore(String player, Integer score){
Match m = findMatchByPlayer(player);
synchronized (m) {
m.printAll();
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));
}
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));
}
}
}

View file

@ -36,7 +36,6 @@ public class ComputeScore implements Callable<Integer> {
System.out.println(match);
System.out.println("COMPUTE SCORE STAsssssRTED");
synchronized (match) {
System.out.print("CALCOLO LO SCORE PER " + match.matchCreator);
Integer score = 0;
@ -54,29 +53,19 @@ public class ComputeScore implements Callable<Integer> {
if(match.allPlayersSendedHisScore()) {
match.matchTimeout.cancel(true);
match.matchTimeout = false;
System.out.println("MATCH TIMEOUT CANCELLATO");
//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());
match.sendScores();
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;
}
}

View file

@ -1,18 +1,11 @@
package com.texttwist.server.tasks;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.texttwist.server.models.Match;
import javafx.util.Pair;
import models.Message;
import javax.swing.*;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
import static com.texttwist.server.components.GameServer.activeMatches;
import static com.texttwist.server.models.Match.findMatch;
/**
* Created by loke on 23/06/2017.
@ -28,7 +21,6 @@ public class JoinMatch implements Callable<Boolean> {
this.socketChannel = socketChannel;
}
@Override
public Boolean call() throws Exception {
final Match thisMatch = Match.findMatch(activeMatches, this.matchName);

View file

@ -2,26 +2,42 @@ package com.texttwist.server.tasks;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
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.
*/
public class MatchTimeout implements Callable<Boolean> {
public MatchTimeout() {
private Match match;
public MatchTimeout(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
try {
Thread.currentThread().sleep(3*60*1000); //TODO 5*60*1000
Thread.currentThread().sleep(1*60*1000); //TODO 5*60*1000
match.setUndefinedScorePlayersToZero();
if(match.matchTimeout) {
System.out.println("SEND BROADCAST BECAUSE TIMEOUT");
match.sendScores();
return true;
}
return false;
} catch (InterruptedException e) {
return true;
return false;
}
}

View file

@ -16,8 +16,8 @@ import java.util.concurrent.Callable;
* Created by loke on 19/06/2017.
*/
public class SendInvitations implements Callable<Boolean> {
private final DefaultListModel<String> users;
private final String sender;
private DefaultListModel<String> users;
private String sender;
public SendInvitations(String sender, DefaultListModel<String> users) {
this.users = users;
@ -27,10 +27,13 @@ public class SendInvitations implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
try {
System.out.println("INVIA INVITO A" + users);
Server.notificationServer.sendInvitations(sender, users);
} catch (Exception e) {
System.out.println("Eccezione" + e);
e.printStackTrace();
}
return true;

View file

@ -1,30 +0,0 @@
package com.texttwist.server.tasks;
import com.texttwist.server.Server;
import com.texttwist.server.components.NotificationServer;
import com.texttwist.server.models.Match;
import constants.Config;
import interfaces.INotificationServer;
import javax.swing.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.concurrent.Callable;
/**
* Created by loke on 19/06/2017.
*/
public class WaitForPlayers implements Callable<Boolean> {
private final Match match;
private String sender;
public WaitForPlayers(Match match) {
this.match = match;
}
@Override
public Boolean call() throws Exception {
return true;
}
}