rendered paste bodypackage main.server;
import java.net.*;
import java.io.*;
import java.util.Date;
import java.text.SimpleDateFormat;
import main.scripting.*;
import main.gui.*;
public class server implements Runnable {
// TODO: yet to figure out proper value for timing, but 500 seems good
public static final int cycleTime = 500;
public static WorldObjectHandler worldObjectHandler;
public server()
{
clientHandler = this;
(new Thread(clientHandler)).start(); // launch server listener
playerHandler = new PlayerHandler();
worldObjectHandler = new WorldObjectHandler();
//new GuiFrame();
int waitFails = 0;
long lastTicks = System.currentTimeMillis();
long totalTimeSpentProcessing = 0;
int cycle = 0;
while(!shutdownServer) {
playerHandler.process();
worldObjectHandler.process();
long timeSpent = System.currentTimeMillis()-lastTicks;
totalTimeSpentProcessing += timeSpent;
if(timeSpent >= cycleTime) {
timeSpent = cycleTime;
if(++waitFails > 100) {
shutdownServer = true;
log("[KERNEL]: machine is too slow to run this server!");
}
}
try {
Thread.sleep(cycleTime-timeSpent);
} catch(Exception e) { }
lastTicks = System.currentTimeMillis();
cycle ++;
if(cycle % 100 == 0) {
float time = ((float)totalTimeSpentProcessing)/cycle;
}
}
playerHandler.destruct();
clientHandler.killServer();
clientHandler = null;
}
public static server clientHandler = null; // handles all the clients
public static ServerSocket clientListener = null;
public static boolean shutdownServer = false; // set this to true in order to shut down and kill the server
public static boolean shutdownClientHandler; // signals ClientHandler to shut down
public static int serverlistenerPort = 43594; //43594=default
public static PlayerHandler playerHandler = null;
public void run() {
try {
shutdownClientHandler = false;
clientListener = new ServerSocket(serverlistenerPort, 1, null);
while(true) {
Socket s = clientListener.accept();
s.setTcpNoDelay(true);
String connectingHost = s.getInetAddress().getHostName();
if(true) {
log("ClientHandler - Accepted from "+ connectingHost +":"+ s.getPort());
playerHandler.newPlayerClient(s, connectingHost);
}
else {
log("ClientHandler - Rejected "+ connectingHost +":"+ s.getPort());
s.close();
}
}
} catch(IOException ioe) {
if(!shutdownClientHandler)
log("Error: Unable to startup listener on "+ serverlistenerPort +" - port already in use?");
else
log("ClientHandler was shut down.");
}
}
public void killServer()
{
try {
shutdownClientHandler = true;
if(clientListener != null) clientListener.close();
clientListener = null;
} catch(Exception e) {
e.printStackTrace();
}
}
public static void sleep(int i) {
try {
Thread.sleep(i);
} catch(Exception e) {
}
}
public static void log(String str) {
String time = new SimpleDateFormat("[hh:mm:ss]").format(new Date());
System.out.println(time +" "+ str);
//OutputArea.log(time +" "+ str);
}
}