package Test;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* A simple Server class
*
* Based on code example from
* http://www.mysamplecode.com/2011/12/java-multithreaded-socket-server.html
* Date of visit: 11.10.2016
*
* @author Marcel Felder
*
*/
public class ServerNew {
//Instance variables
ServerSocket serverSocket;
boolean ServerOn = true;
private ArrayList<PrintStream> list_clientWriter;
private ArrayList<Socket> list_clientSockets;
private Map<Integer, String> map_id_name = new HashMap<Integer, String>();
int port = 16003;
int clientId = 0;
private static final int MAX_CLIENT = 2; //This server can accept up to MAX_CLIENT clients' connection
//Main object of the server instance
public ServerNew() {
try {
serverSocket = new ServerSocket(port);
appendTextToConsole("Server created. Port: " + port);
//list_clientWriter = new ArrayList<PrintStream>();
list_clientSockets = new ArrayList<Socket>();
}
catch(IOException ioe) {
appendTextToConsole("Could not create ServerSocket on port " + port + ". Quitting.");
System.exit(-1);
}
//Ausgabe Zeit des Erstellen des Server
Calendar now = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
appendTextToConsole("ServerSocket created: " + formatter.format(now.getTime()));
// Successfully created Server Socket. Now wait for connections.
while(ServerOn) {
listenToClients();
} try {
serverSocket.close();
appendTextToConsole("Server stopped");
}catch(Exception e) {
appendTextToConsole("Problem stopping ServerSocket");
System.exit(-1);
}
}
/**
* Method where Server accepts several clients.
* For each ClientSocket a new ClientServiceThread
* will be started.
*/
public void listenToClients() {
while (clientId < 2) {
appendTextToConsole("Server waits for incoming clients");
try {
clientId++;
Socket clientSocket = serverSocket.accept();
list_clientSockets.add(clientSocket);
appendTextToConsole("Client " + clientId + " hinzugefuegt.");
// Start a service thread
ClientServiceThread clientThread = new ClientServiceThread(clientSocket, clientId);
clientThread.start();
} catch(IOException ioexception) {
appendTextToConsole("Exception encountered on accept. Ignoring. Stack Trace :");
ioexception.printStackTrace();
}
if (clientId == MAX_CLIENT) {
appendTextToConsole("Spiel wird gestartet");
sendToOneClient(0, "Dein Zug");
sendToOneClient(1, "Name des Gegners #" + map_id_name.get(1));
sendToOneClient(0, "Name des Gegners #" + map_id_name.get(2));
}
}
}
/**
* Method to show text in server console
*
* @param message
* the text to be showed in console
*/
public void appendTextToConsole(String message) {
System.out.println(message);
}
/**
* Method to send a message to only one client
*
* @param index
* the index of the print writer.
* @param message
* the message for the client
* @throws IOException
*/
public void sendToOneClient(int index, String message) {
PrintStream writer;
try {
writer = list_clientWriter.get(index);
writer.println(message);
writer.flush();
}catch (Exception e) {
System.err.println("IOException: " + e);
}
}
/**
* Method to send message to all clients
*
* @param message
* the message which has to be sent to all clients
* @throws IOException
*/
public void sendToAllClients(String message) throws IOException {
Iterator<PrintStream> it = list_clientWriter.iterator();
while (it.hasNext()) {
PrintStream writer = (PrintStream) it.next();
writer.println(message);
writer.flush();
}
}
/**
* Method to add a player name, according to the client id, to the HashMap
*
* @param id
* the id of the connected socket
* @param name
* the player name to be added
*/
public void addPlayername(int id, String name) {
map_id_name.put(id, name);
}
//Main method to start the server
public static void main (String[] args)
{
new ServerNew();
}
//-----------New Class-----------//
/**
* A class, which listens to incoming messages from client and interprets them.
*
* @author Marcel Felder
*
*/
public class ClientServiceThread extends Thread {
//Instance variables
Socket ClientSocket;
int ClientId;
boolean RunThread = true;
private DataInputStream inFromClient = null;
private PrintStream outToClient = null;
public ClientServiceThread() {
super();
}
public ClientServiceThread(Socket s, int id) {
this.ClientSocket = s;
this.ClientId = id;
}
public void run() {
String clientMessage;
try {
inFromClient = new DataInputStream(ClientSocket.getInputStream());
outToClient = new PrintStream(ClientSocket.getOutputStream());
outToClient.println("Hello Client " + clientId + ", schön bist du hier!");
list_clientWriter = new ArrayList<PrintStream>();
list_clientWriter.add(outToClient);
// At this point, we can read for input and reply with appropriate output.
// Run in a loop until RunThread is set to false
while(RunThread) {
if(!ServerOn)
{
// Special command. Quit this thread
appendTextToConsole("Server has already stopped");
outToClient.println("Server has already stopped");
outToClient.flush();
RunThread = false;
}
// read incoming stream
while ((clientMessage = inFromClient.readLine()) != null) {
appendTextToConsole("Client " + ClientId + " says :" + clientMessage);
//TEST FÜRS SENDEN!!
if(clientMessage.equals("hello")){
appendTextToConsole("es geht bis hier");
//bis hier gehts, danach kann der text nicht zurück an den sender
//gesendet werden! checken warum?
outToClient.println("it works");
}
// Interpreting the messages
if(clientMessage.equals("switchTurn")){
if(this.ClientId == 1){
sendToOneClient(1, "Your turn");
sendToAllClients(clientMessage);
} else if(this.ClientId == 2){
sendToOneClient(0, "Your turn");
sendToAllClients(clientMessage);
}
}else if(clientMessage.contains("won")){
if(this.ClientId == 1){
sendToOneClient(1, clientMessage);
sendToAllClients("Game is over");
} else if(this.ClientId == 2){
sendToOneClient(0, clientMessage);
sendToAllClients("Game is over");
}
}else if(clientMessage.equalsIgnoreCase("quit")){
// Special command. Quit this thread
RunThread = false;
appendTextToConsole("Stopping client thread for client: " + ClientId);
}
else if(clientMessage.equalsIgnoreCase("end")) {
// Special command. Quit this thread and Stop the Server
RunThread = false;
appendTextToConsole("Stopping client thread for client: " + ClientId);
ServerOn = false;
appendTextToConsole("Server stopped ");
}
else{
sendToAllClients(clientMessage);
outToClient.flush();
}
}
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
// Clean up
try {
inFromClient.close();
outToClient.close();
ClientSocket.close();
System.out.println("...Stopped");
} catch(IOException ioexception) {
ioexception.printStackTrace();
}
}
}
}
}