Added serverSocketChannel for game creation

This commit is contained in:
Lorenzo Iovino 2017-06-18 14:13:31 +02:00
parent 546e341433
commit 48705f7e76
30 changed files with 1787 additions and 606 deletions

View file

@ -1,7 +1,6 @@
package com.texttwist.server;
import com.texttwist.server.components.TTServer;
import utilities.TTLogger;
import utilities.Logger;
import java.io.File;
import java.io.IOException;
@ -9,10 +8,6 @@ import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("Server start");
TTLogger logger = new TTLogger(new File("./log"));
TTServer ttServer = new TTServer();
ttServer.start();
Server ttServer = new Server();
}
}

View file

@ -0,0 +1,45 @@
package com.texttwist.server;
import com.texttwist.server.components.Auth;
import com.texttwist.server.components.GameServer;
import utilities.Logger;
import java.io.File;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
* Created by loke on 15/06/2017.
*/
public class Server {
public Server() throws IOException {
//Start services
Logger logger = new Logger(new File("./server.log"), "Server");
Logger.write("Server starting ...");
try {
//Definitions of registry for auth
Auth auth = new Auth(9999);
Registry registry = LocateRegistry.createRegistry(auth.serverPort);
registry.bind("auth", auth);
GameServer server = new GameServer(10000);
new Thread(server).start();
Logger.write("Server started");
} catch (RemoteException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,52 @@
package com.texttwist.server.components;
import models.Account;
import models.Session;
import models.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Created by loke on 18/06/2017.
*/
public class AccountsManager {
private List<Account> accounts = Collections.synchronizedList(new ArrayList<Account>());
private static class Holder {
static final AccountsManager INSTANCE = new AccountsManager();
}
public static AccountsManager getInstance() {
return AccountsManager.Holder.INSTANCE;
}
private AccountsManager(){}
public boolean register(String userName, String password) {
if(!exists(userName)){
return accounts.add(new Account(userName, password));
} else {
return false;
}
}
public boolean exists(String userName) {
synchronized(accounts) {
Iterator<Account> i = accounts.iterator();
while (i.hasNext()) {
if (i.next().userName.equals(userName)) {
return true;
}
}
return false;
}
}
public int size(){
return accounts.size();
}
}

View file

@ -0,0 +1,80 @@
package com.texttwist.server.components;
import interfaces.IAuth;
import models.Account;
import models.Response;
import org.json.simple.JsonObject;
import utilities.Logger;
import java.math.BigInteger;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.SecureRandom;
/**
* Created by loke on 15/06/2017.
*/
public class Auth extends UnicastRemoteObject implements IAuth {
private SecureRandom random = new SecureRandom();
public int serverPort = 9999;
public Auth(int serverPort) throws RemoteException{
this.serverPort=serverPort;
Logger.write("Auth Service running at "+serverPort+" port...");
}
@Override
public Response register(String userName, String password) throws RemoteException {
Logger.write("Invoked register with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
if(AccountsManager.getInstance().register(userName, password)){
Logger.write("Registration successfull");
return new Response("Registration successfull", 200, null);
} else {
Logger.write("Registration unsuccessfull");
return new Response("Registration unsuccessfull: Username exist!", 400, null);
}
}
return new Response("Registration unsuccessfull! All fields are mandatories", 400, null);
}
@Override
public Response login(String userName, String password) throws RemoteException {
Logger.write("Invoked login with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
if(AccountsManager.getInstance().exists(userName)) {
JsonObject data = new JsonObject();
String token = nextSessionId();
data.put("token", token);
SessionsManager.getInstance().add(userName,token);
Logger.write("Login successfull");
return new Response("Login successfull", 200, data);
}
}
Logger.write("Login unsuccessfull");
return new Response("Login unsuccessfull", 400, null);
}
@Override
public Response logout(String userName, String token) throws RemoteException {
Logger.write("Invoked logout with username=" + userName + " AND " + " token=" + token);
if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) {
SessionsManager.getInstance().remove(userName);
Logger.write("Logout successfull");
return new Response("Logout successfull", 200, null);
}
SessionsManager.getInstance().remove(userName);
Logger.write("Logout successfull (but something gone wrong)");
return new Response("Logout successfull (but something gone wrong)", 200, null);
}
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}

View file

@ -0,0 +1,129 @@
package com.texttwist.server.components;
import com.sun.org.apache.xpath.internal.operations.Bool;
import jdk.nashorn.internal.parser.JSONParser;
import org.json.simple.JsonObject;
import utilities.Logger;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.*;
import static java.nio.channels.SelectionKey.OP_ACCEPT;
import static java.nio.channels.SelectionKey.OP_READ;
public class GameServer implements Runnable{
protected int serverPort;
protected ServerSocketChannel serverSocketChannel = null;
protected ThreadProxy proxy;
protected Selector selector = null;
protected JsonObject msg = null;
public GameServer(int port){
this.serverPort = port;
}
public void run(){
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
selector = Selector.open();
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(serverPort));
serverSocketChannel.register(selector, OP_ACCEPT);
Logger.write("Game Service is running at "+this.serverPort+" port...");
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
selector.select();
} catch (IOException e) {
e.printStackTrace();
}
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
while (iter.hasNext()) {
SocketChannel client;
SelectionKey key = iter.next();
iter.remove();
try {
switch (key.readyOps()) {
case OP_ACCEPT:
client = ((ServerSocketChannel) key.channel()).accept();
client.configureBlocking(false);
client.register(selector, OP_READ);
break;
case OP_READ:
client = (SocketChannel) key.channel();
buffer.clear();
if (client.read(buffer) != -1) {
buffer.flip();
String line = new String(buffer.array(), buffer.position(), buffer.remaining());
proxy = new ThreadProxy(JSONParser.quote(line));
Thread t = new Thread(proxy);
t.start();
if (line.startsWith("CLOSE")) {
client.close();
} else if (line.startsWith("QUIT")) {
for (SelectionKey k : selector.keys()) {
k.cancel();
k.channel().close();
}
selector.close();
return;
}
} else {
key.cancel();
}
break;
default:
System.out.println("unhandled " + key.readyOps());
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/* try {
this.serverSocket = new ServerSocket(this.serverPort);
Logger.write("Game Service is running at "+this.serverPort+" port...");
} catch (IOException e) {
e.printStackTrace();
}
while(true){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
proxy = new ThreadProxy(clientSocket);
Thread t = new Thread(proxy);
t.start();
*/
// threadPool.shutdown(); // shutdown the pool.
//this.threadPool.execute(new ThreadWorker(clientSocket, "TASK DI PROVA"));
}
}
}

View file

@ -0,0 +1,54 @@
package com.texttwist.server.components;
import models.Account;
import models.Session;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
/**
* Created by loke on 17/06/2017.
*/
public class SessionsManager {
private List<Session> sessions = Collections.synchronizedList(new ArrayList<Session>());
private static class Holder {
static final SessionsManager INSTANCE = new SessionsManager();
}
public static SessionsManager getInstance() {
return Holder.INSTANCE;
}
private SessionsManager(){}
public boolean add(String userName, String token) {
remove(userName);
return sessions.add(new Session(userName, token));
}
public boolean remove(String userName){
return sessions.remove(exists(userName));
}
public Session exists(String userName) {
synchronized(sessions) {
Iterator<Session> i = sessions.iterator();
while (i.hasNext()) {
Session elem = i.next();
if (elem.userName.equals(userName)) {
return elem;
}
}
return null;
}
}
public int size(){
return sessions.size();
}
}

View file

@ -1,34 +0,0 @@
package com.texttwist.server.components;
import com.texttwist.server.components.auth.TTAuth;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
/**
* Created by loke on 15/06/2017.
*/
public class TTServer {
private static final int PORT = 9999;
public void start() {
try {
TTAuth auth = new TTAuth();
Registry registry = LocateRegistry.createRegistry(PORT);
registry.bind("auth", auth);
System.out.println("Auth Service running at "+PORT+" port...");
} catch (RemoteException e) {
System.out.println(e.getMessage());
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,60 @@
package com.texttwist.server.components;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;
/**
* Created by loke on 18/06/2017.
*/
public class ThreadProxy implements Runnable {
protected ExecutorService threadPool = Executors.newCachedThreadPool();
private String request;
ThreadProxy(String request){
this.request = request;
}
private Callable<Boolean> checkIfUsersAreOnline = new Callable<Boolean>(){
String message = "Check If users are online!";
@Override
public Boolean call() throws Exception {
for(int i = 0; i < 1; i++){
Thread.sleep(2000);
}
return true;
}
};
public void run() {
System.out.println("Selecting right task for new thread");
/* byte[] buffer = new byte[100];
try {
InputStream clientInputStream = clientSocket.getInputStream();
while (clientInputStream.read(buffer) != -1) {
request += buffer;
}
System.out.println(request);
} catch (IOException e) {
e.printStackTrace();
}
*/
//Assegna un threadWorker al task in arrivo
System.out.print(request);
Future<Boolean> callableFuture = threadPool.submit(checkIfUsersAreOnline);
try {
// get() waits for the task to finish and then gets the result
Boolean returnedValue = callableFuture.get();
System.out.println(returnedValue);
} catch (InterruptedException e) {
// thrown if task was interrupted before completion
e.printStackTrace();
} catch (ExecutionException e) {
// thrown if the task threw an execption while executing
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,41 @@
package com.texttwist.server.components;
import utilities.Logger;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import static java.lang.Thread.sleep;
public class ThreadWorker implements Runnable{
protected Socket clientSocket = null;
protected String task = null;
public ThreadWorker(Socket clientSocket, String task) {
this.clientSocket = clientSocket;
this.task = task;
}
public void run() {
Logger.write(Thread.currentThread().getName()+": Start task -> " + task);
try {
sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
/* InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nThreadWorker: " +
this.serverText + " - " +
time +
"").getBytes());
output.close();
input.close();*/
Logger.write(Thread.currentThread().getName()+": End of task -> " + task);
}
}

View file

@ -1,74 +0,0 @@
package com.texttwist.server.components.auth;
import interfaces.ITTAuth;
import models.TTResponse;
import org.json.simple.JsonObject;
import utilities.TTLogger;
import java.math.BigInteger;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.security.SecureRandom;
/**
* Created by loke on 15/06/2017.
*/
public class TTAuth extends UnicastRemoteObject implements ITTAuth {
private SecureRandom random = new SecureRandom();
public TTAuth() throws RemoteException{
}
@Override
public TTResponse register(String userName, String password) throws RemoteException {
TTLogger.write("LOGGER: Invoked register with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
boolean res = true;//TODO Inserisci nel db e verifica se c'è un utente con lo stesso nome
if(userName.equals("ciro")){ //TODO rimuovere
res = false;
}
if(res) {
TTLogger.write("LOGGER: Registration successfull");
return new TTResponse("Registration successfull", 200, null);
} else {
TTLogger.write("LOGGER: Registration unsuccessfull");
return new TTResponse("Registration unsuccessfull: Username exist!", 400, null);
}
}
return new TTResponse("Registration unsuccessfull! All fields are mandatories", 400, null);
}
@Override
public TTResponse login(String userName, String password) throws RemoteException {
TTLogger.write("LOGGER: Invoked login with username=" + userName + " AND " + " password=" + password);
if ((userName != null && !userName.isEmpty()) && (password != null && !password.equals(""))) {
if((userName.equalsIgnoreCase("admin"))
&& (password.equals("admin"))) {
JsonObject data = new JsonObject();
data.put("token", nextSessionId());
TTLogger.write("LOGGER: Login successfull");
return new TTResponse("Login successfull", 200, data);
}
}
return new TTResponse("Login unsuccessfull", 400, null);
}
@Override
public TTResponse logout(String userName, String token) throws RemoteException {
TTLogger.write("LOGGER: Invoked logout with username=" + userName + " AND " + " token=" + token);
if ((userName != null && !userName.isEmpty()) && (token != null && !token.isEmpty())) {
return new TTResponse("Logout successfull", 200, null);
}
return new TTResponse("Logout successfull (but something gone wrong)", 200, null);
}
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}