package edu.ups.gamedev.net;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import com.captiveimagination.jgn.JGN;
import com.captiveimagination.jgn.clientserver.JGNServer;
import com.captiveimagination.jgn.event.MessageListener;
import com.captiveimagination.jgn.message.Message;
import com.captiveimagination.jgn.synchronization.SynchronizationManager;
import com.captiveimagination.jmenet.JMEGraphicalController;
/**
* Encapsilates everything needed to run a networked server for a JGN game. It currently
* relies on serialization, but this is relatively slow and so may need to be replaced
* with a more efficient approach if it is noticably slow.
*
* @author Walker Lindley
* @version $Revision: 1.3 $, $Date: 2008/01/29 23:58:45 $
*
*/
public class Server extends NetworkCommon {
JGNServer server; //this is our primary server and the addresses it should use
/**
* Constructor that takes a root node and uses default values for the server
* addresses.
*
* @param root root node of the scene graph
* @throws IOException
*/
public Server() throws UnknownHostException, IOException {
super((InetAddress)null);
System.out.println("Creating server with address " + serverFast);
try {
createServer(); //initialize everything
} catch (IOException e) {
throw new IOException("Couldn't create JGN server");
}
}
/**
* Creates and initializes all of the objects necessary for the server.
*
* @throws IOException
*/
private void createServer() throws IOException {
//create the addresses (really just ports) the server will use
try {
server = new JGNServer(serverReliable, serverFast);
} catch (IOException e) {
System.err.println("Couldn't create JGN server");
e.printStackTrace();
return;
}
controller = new JMEGraphicalController(); //in charge of generating and applying sync messages
syncManager = new SynchronizationManager(server, controller); //create the server that will send and receive sync messages
syncManager.addSyncObjectManager(this);
Thread tmp = JGN.createThread(server); //create a new thread for the server and start it
childThreads.add(tmp);
tmp.start();
tmp = JGN.createThread(syncManager); //create and start a thread for the synchronization manager
childThreads.add(tmp);
tmp.start();
//attach a MessageListener so that we can get more detailed information about what the server is doing
server.getReliableServer().addMessageListener(new MessageListener() {
public void messageCertified(Message message) {
System.out.println("Message Certified: " + message);
}
public void messageFailed(Message message) {
System.out.println("Message Failed: " + message);
}
public void messageReceived(Message message) {
System.out.println("Message Received: " + message);
}
public void messageSent(Message message) {
System.out.println("Message Sent: " + message);
}
});
}
public void kill() {
super.kill();
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public JGNServer getJGNServer() {
return server;
}
}