This commit is contained in:
Lorenzo Iovino 2017-07-14 00:06:59 +02:00
parent 71ff3c4820
commit e1622dfaa1
17 changed files with 463 additions and 561 deletions

View file

@ -59,7 +59,7 @@ public class Server {
private void startMessageService(){
//Starting the Message service based on TCP
new Thread(new MessageService(Config.GameServerPort)).start();
new Thread(new MessageService()).start();
}
private void startWordsReceiverService(){

View file

@ -10,8 +10,6 @@ import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static com.texttwist.server.services.MessageService.activeMatches;
/**
* Author: Lorenzo Iovino on 23/06/2017.
@ -32,6 +30,9 @@ public class Match {
//Players score: A list of pair where elements are <playerName, score>.
public final List<Pair<String,Integer>> playersScore = Collections.synchronizedList(new ArrayList<>());
//Players score: A list of active matches.
public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
/****SINGLE INSTANCE OF MATCH****/
//If match is started
@ -50,7 +51,7 @@ public class Match {
//Letters of the match
public DefaultListModel<String> letters;
protected ExecutorService matchTimeoutThread = Executors.newSingleThreadExecutor();
private ExecutorService matchTimeoutThread = Executors.newSingleThreadExecutor();
public Match(String matchCreator, DefaultListModel<String> players){
for (int i =0; i < players.size(); i++){
@ -61,7 +62,6 @@ public class Match {
this.multicastId = this.generateMulticastId();
this.matchCreator = matchCreator;
}
public static Match findMatch(List<Match> matches, String matchName){
@ -73,12 +73,6 @@ public class Match {
return null;
}
public void printAll(){
for (Pair<String, Integer> aPlayersScore : playersScore) {
System.out.println(aPlayersScore.getKey() + " : " + aPlayersScore.getValue());
}
}
public static int findMatchIndex(List<Match> matches, String matchName){
for (int i = 0; i < matches.size(); i++) {
if (matches.get(i).matchCreator.equals(matchName)) {

View file

@ -1,4 +1,4 @@
package com.texttwist.server.servers;
package com.texttwist.server.proxies;
import com.texttwist.server.services.SessionsService;
import com.texttwist.server.models.Match;
@ -10,25 +10,22 @@ import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.*;
import static com.texttwist.server.services.MessageService.activeMatches;
/**
* Author: Lorenzo Iovino on 18/06/2017.
* Description: Proxy Dispatcher
* */
public class ProxyDispatcher implements Callable<Boolean> {
protected final ExecutorService threadPool = Executors.newCachedThreadPool();
public class MessageDispatcher implements Callable<Boolean> {
private final ExecutorService threadPool = Executors.newCachedThreadPool();
private final Message request;
private final SocketChannel socketChannel;
private ByteBuffer bufferMessage;
boolean matchNotAvailable =false;
private boolean matchNotAvailable = false;
public ProxyDispatcher(Message request, SocketChannel socketChannel, ByteBuffer bufferMessage) {
public MessageDispatcher(Message request, SocketChannel socketChannel, ByteBuffer bufferMessage) {
this.request = request;
this.socketChannel = socketChannel;
this.bufferMessage = bufferMessage;
}
@Override
@ -47,12 +44,10 @@ public class ProxyDispatcher implements Callable<Boolean> {
Boolean invitationSended = sendInvitations.get();
if (invitationSended) {
//Crea nuova partita e attendi i giocatori
//Create new match and wait users joins
request.data.addElement(request.sender);
final Match match = new Match(request.sender, request.data);
match.printAll();
activeMatches.add(match);
Match.activeMatches.add(match);
DefaultListModel<String> matchName = new DefaultListModel<>();
matchName.addElement(request.sender);
@ -62,28 +57,24 @@ public class ProxyDispatcher implements Callable<Boolean> {
if(!joinMatchRes){
bufferMessage = ByteBuffer.allocate(1024);
//NON FARE NULLA, ASPETTA GLI ALTRI
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));
Boolean joinTimeoutRes = joinTimeout.get();
if(joinTimeoutRes){
Future<Boolean> sendMessageJoinTimeout = threadPool.submit(
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
new SendMessageToAllPlayers(match,
new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
if(!sendMessageJoinTimeoutRes){
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
Match.activeMatches.remove(Match.findMatchIndex(Match.activeMatches, match.matchCreator));
return sendMessageJoinTimeoutRes;
}
} else {
System.out.println("TIMEOUT FINITO SENZA EFFETTI");
return true;
}
@ -124,7 +115,6 @@ public class ProxyDispatcher implements Callable<Boolean> {
bufferMessage = ByteBuffer.wrap(byteMessage);
try {
String s = new String(bufferMessage.array(), bufferMessage.position(), bufferMessage.remaining());
socketChannel.write(bufferMessage);
} catch (IOException e) {
e.printStackTrace();
@ -139,7 +129,7 @@ public class ProxyDispatcher implements Callable<Boolean> {
case "JOIN_GAME":
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel));
try {
Match match = Match.findMatch(activeMatches, request.data.get(0));;
Match match = Match.findMatch(Match.activeMatches, request.data.get(0));;
Boolean joinMatchRes = joinMatch.get();
if(joinMatchRes){
@ -153,23 +143,17 @@ public class ProxyDispatcher implements Callable<Boolean> {
if (socketClient != null) {
bufferMessage.clear();
bufferMessage = ByteBuffer.allocate(1024);
Message message = new Message("GAME_STARTED", "", "", match.letters);
match.startGame();
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) {
e.printStackTrace();
}
}
}
if (matchNotAvailable) {
return false;
@ -180,7 +164,6 @@ public class ProxyDispatcher implements Callable<Boolean> {
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();
@ -188,7 +171,6 @@ public class ProxyDispatcher implements Callable<Boolean> {
socketChannel.write(bufferMessage);
matchNotAvailable = true;
}
}
}
} catch (InterruptedException e) {
@ -198,17 +180,13 @@ public class ProxyDispatcher implements Callable<Boolean> {
} catch (IOException e) {
e.printStackTrace();
}
default:
break;
}
} else {
threadPool.submit(new TokenInvalid(request.sender, socketChannel, bufferMessage));
return false;
}
return false;
}
}

View file

@ -16,10 +16,6 @@ import static com.texttwist.server.Server.jedisPool;
*/
public class JedisService {
public JedisService(){
}
/** Read the object from Base64 string. */
public static Object fromString(String s) throws IOException, ClassNotFoundException {
byte [] data = Base64.getDecoder().decode(s);
@ -57,11 +53,8 @@ public class JedisService {
Jedis jedis = null;
List<Serializable> l = new ArrayList<>();
try {
System.out.println("USER ss");
jedis = jedisPool.getResource();
String usersString = jedis.get(key);
System.out.println("USER "+usersString);
if(usersString!=null) {
String[] lines = usersString.split("\n");
for (int i = 0; i < lines.length; i++) {

View file

@ -1,76 +1,53 @@
package com.texttwist.server.services;
import com.texttwist.server.Server;
import com.texttwist.server.servers.ProxyDispatcher;
import com.texttwist.server.proxies.MessageDispatcher;
import com.texttwist.server.models.Dictionary;
import com.texttwist.server.models.Match;
import constants.Config;
import models.Message;
import java.net.*;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.nio.channels.SelectionKey.OP_ACCEPT;
import static java.nio.channels.SelectionKey.OP_READ;
/**
* Author: Lorenzo Iovino on 17/06/2017.
* Description: Game Server
* Description: Message Service
*/
public class MessageService implements Runnable{
private int serverPort;
private ProxyDispatcher proxy;
private ReceiveWordsService wordsReceiver;
private DatagramChannel datagramChannel;
private Selector selector = null;
private ExecutorService threadPool = Executors.newCachedThreadPool();
private ExecutorService dispatcherPool = Executors.newCachedThreadPool();
private String dictionaryPath = "./Server/resources/dictionary";
public static Dictionary dict;
SocketChannel client;
ByteBuffer bufferWords = ByteBuffer.allocate(1024);
ByteBuffer bufferMessages = ByteBuffer.allocate(1024);
public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
public static Integer multicastId = 4000;
public MessageService(int port){
this.serverPort = port;
}
public void run(){
public MessageService()
{
dict = new Dictionary(dictionaryPath);
try {
selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(serverPort));
serverSocketChannel.socket().bind(new InetSocketAddress(Config.GameServerPort));
serverSocketChannel.register(selector, OP_ACCEPT);
Server.logger.write("GameService Service is running at "+this.serverPort+" port...");
Server.logger.write("GameService Service is running at "+Config.GameServerPort+" port...");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run(){
while (true) {
System.out.println("WAITING FOR MSG");
try {
selector.select();
} catch (IOException e) {
@ -79,9 +56,9 @@ public class MessageService implements Runnable{
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
bufferMessages = ByteBuffer.allocate(1024);
ByteBuffer bufferMessages = ByteBuffer.allocate(1024);
bufferMessages.clear();
client = null;
SocketChannel client = null;
SelectionKey key = iter.next();
iter.remove();
@ -99,10 +76,9 @@ public class MessageService implements Runnable{
bufferMessages.flip();
String line = new String(bufferMessages.array(), bufferMessages.position(), bufferMessages.remaining());
if (line.startsWith("MESSAGE")) {
SessionsService.getInstance().printAll();
Message msg = Message.toMessage(line);
proxy = new ProxyDispatcher(msg, client, bufferMessages);
threadPool.submit(proxy);
MessageDispatcher proxy = new MessageDispatcher(msg, client, bufferMessages);
dispatcherPool.submit(proxy);
}
if (line.startsWith("CLOSE")) {

View file

@ -25,32 +25,21 @@ public class NotificationService implements INotificationServer {
public synchronized void registerForCallback(INotificationClient clientInterface) throws RemoteException {
if(!clients.contains(clientInterface)){
clients.add(clientInterface);
System.out.println(clientInterface);
System.out.println("New client registered");
}
}
public synchronized void unregisterForCallback(INotificationClient client) throws RemoteException {
if (clients.remove(client)) {
System.out.println("Client unregistered");
} else {
System.out.println("Unable to unregister client");
}
clients.remove(client);
}
public synchronized void sendInvitations(String username, DefaultListModel<String> users){
Iterator i = clients.iterator();
INotificationClient client = null;
System.out.println("Starting callbacks");
while (i.hasNext()) {
client = (INotificationClient) i.next();
try {
System.out.println("SENDING INVITE TO "+users);
client.sendInvite(username, users);
} catch (RemoteException e) {
System.out.println("Sembra down");
try {
unregisterForCallback(client);
} catch (RemoteException e1) {

View file

@ -40,12 +40,6 @@ public class SessionsService {
return sessions.add(new Session(new User(userName,"",0), token));
}
public void printAll(){
for (Session elem : sessions) {
System.out.println(elem.account.userName + " | " + elem.token);
}
}
public boolean remove(String userName){
if(exists(userName)) {
Session s = getSession(userName);

View file

@ -14,10 +14,10 @@ import java.util.concurrent.Callable;
*/
public class ComputeScore implements Callable<Integer> {
public DefaultListModel<String> words;
public final String sender;
private DefaultListModel<String> words;
private final String sender;
public Match match;
public DefaultListModel<String> wordsValid;
private DefaultListModel<String> wordsValid;
public ComputeScore(String sender, DefaultListModel<String> words, Match match){
this.words = words;
@ -33,31 +33,18 @@ public class ComputeScore implements Callable<Integer> {
for (int i = 0; i < words.size(); i++) {
if (isValid(words.get(i), match.letters)) {
score += words.get(i).length();
System.out.println(words.get(i) + " is valid!" + " : " + score );
wordsValid.addElement(words.get(i));
}
}
System.out.println(sender +" totalize SCORE = " + score);
match.setScore(sender, score);
for (Pair<String, Integer> player : match.playersScore) {
System.out.println(player.getValue());
}
System.out.println(score);
User u = AccountsService.getInstance().findUser(sender);
u.addScore(score);
if(match.allPlayersSendedHisScore()) {
match.matchTimeout = false;
System.out.println("MATCH TIMEOUT CANCELLATO");
match.setUndefinedScorePlayersToZero();
new SendScores(match).call();
}
return score;
}
@ -74,7 +61,6 @@ public class ComputeScore implements Callable<Integer> {
if(word.equals("")){
return true;
}
if(!isCharacterPresent || wordsValid.indexOf(word)!=-1){
return false;
}

View file

@ -5,7 +5,6 @@ import javafx.util.Pair;
import javax.swing.*;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Callable;
import static com.texttwist.server.services.MessageService.activeMatches;
/**
* Author: Lorenzo Iovino on 23/06/2017.
@ -24,7 +23,7 @@ public class JoinMatch implements Callable<Boolean> {
@Override
public Boolean call() throws Exception {
final Match thisMatch = Match.findMatch(activeMatches, this.matchName);
final Match thisMatch = Match.findMatch(Match.activeMatches, this.matchName);
if (thisMatch != null) {
for (int j = 0; j < thisMatch.playersStatus.size(); j++) {
String name = thisMatch.playersStatus.get(j).getKey();
@ -40,25 +39,12 @@ public class JoinMatch implements Callable<Boolean> {
return false;
}
private void printAll(Match match){
for (int i = 0; i < match.playersStatus.size(); i++) {
System.out.println(match.playersStatus.get(i).getKey());
System.out.println(match.playersStatus.get(i).getValue());
System.out.println(match.playersSocket.get(i).getKey());
System.out.println(match.playersSocket.get(i).getValue());
}
}
private Boolean allJoined(Match match) {
for (int i = 0; i < match.playersStatus.size(); i++) {
if (match.playersStatus.get(i).getValue() == 0) {
return false;
}
}
match.printAll();
match.joinTimeout = false;
return true;
}

View file

@ -21,12 +21,9 @@ 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();
}

View file

@ -10,8 +10,6 @@ import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.concurrent.Callable;
import static com.texttwist.server.services.MessageService.activeMatches;
/**
* Created by loke on 13/07/2017.
*/
@ -27,9 +25,7 @@ public class SendScores implements Callable<Void> {
public Void call() throws Exception {
while (true) {
System.out.println("SENDING");
Message msg = new Message("FINALSCORE", "SERVER", "", match.getMatchPlayersScoreAsStringList());
MulticastSocket multicastSocket = null;
try {
multicastSocket = new MulticastSocket(match.multicastId);
@ -39,7 +35,7 @@ public class SendScores implements Callable<Void> {
} catch (IOException e) {
e.printStackTrace();
}
activeMatches.remove(Match.findMatchIndex(activeMatches, match.matchCreator));
Match.activeMatches.remove(Match.findMatchIndex(Match.activeMatches, match.matchCreator));
return null;
}
}