1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| public class Server {
// list of the Players connected
protected final List <Player> connections = new ArrayList<Player>();
// list of the IP connected and waiting for logins
protected final List <Socket> ipWaiting = new ArrayList<Socket>();
// port of the application
protected int port = 1991;
// objects connections
protected final Connections con = new Connections();
public Server() throws IOException{
Thread t = new DaemonThread();
}
class DaemonThread extends Thread{
public DaemonThread(){
//start the main thread
start();
}
@Override
public void run(){
Socket skt = null;
ServerSocket srvr = null;
try {
//open the port
srvr = new ServerSocket(port);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
while(true){
int result = 0;
try{
//accept the connections
skt = srvr.accept();
System.out.print("New connection ! \n");
//check in address if the client is already connected
result = ipWaitingChanges(skt, "check");
//error
}catch(IOException ioe){
System.out.print("It didn't work! - "+ioe.getMessage()+"\n");
ioe.printStackTrace();
ipWaitingChanges(skt, "kill");
}
if(result == 1){
//if no error :
ipWaitingChanges(skt, "add");
}
}
}
}
class ServerData implements Runnable{
private Socket skt;
protected Player player = null;
private Network network;
private cmdToServer cts;
public ServerData(Socket skt) throws IOException{
//init
this.skt = skt;
network = new Network(this.skt);
cts = new cmdToServer();
// number of thread
System.out.println("Number of thread : "+Thread.activeCount());
}
public void run(){
try{
try {
try {
//analyse the packet juste receive
cts.analyse((Object) network.readObject(), network);
} catch (SQLException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}catch(IOException ioe){
//if error :
//close the connection
System.out.print("It didn't work! - "+ioe.getMessage()+"\n");
ioe.printStackTrace();
if(getPlayerFromSocket(skt) != null){
//if he is already login in
removePlayer(getPlayerFromSocket(skt), network);
}else{
//if not
}
}
}
} |
Partager