public NetDaemon(boolean isServer, Game gameData, ConnectionInProgress cip, Controller cont) { setDaemon(true); playersServerSide = new ArrayList<String>(); opponentResponse = false; serverResponse = false; ready = false; this.isServer = isServer; this.gameData = gameData; this.cont = cont; if (isServer) clients = cont.getGuestPlayers() + cont.getHostPlayers() - 1; clientsJoined = 0; players = clients; this.cip = cip; setPriority(Thread.MIN_PRIORITY); services = new ArrayList<ServerService>(); responseFromServer = null; requestToServer = null; sSocket = null; mw = null; shouldRun = true; }
public void run() { if (isServer) { try { sSocket = new ServerSocket(portNr); } catch (IOException e) { e.printStackTrace(); } while (shouldRun) { try { Socket s = sSocket.accept(); ServerService c = new ServerService(s, gameData, this, cont); services.add(c); c.start(); clientsJoined++; System.out.println( clientsJoined + " " + cont.getHostPlayers() + " " + cont.getGuestPlayers()); if (clientsJoined == cont.getHostPlayers() + cont.getGuestPlayers() - 1) { System.out.println("ready"); ready = true; } } catch (IOException e) { e.printStackTrace(); } } for (ServerService a : services) a.setShouldRun(false); } else { while (shouldRun) { try { String response = responseFromServer.readLine(); if (response.startsWith("spl")) { spl = response.substring(3); serverResponse = true; } if (response.startsWith("opl")) { opponentResponse = true; opl = response.substring(3); } if (response.startsWith("gamechallenge")) serverGameData = response; if (response.equals("sidefull")) cs.playerNotAdded(); if (response.equals("playeradded")) cs.playerAdded(); if (response.startsWith("chat")) { parseChatMessage(response); } if (response.startsWith("water")) { waterResponse(response); } if (response.startsWith("hit")) { System.out.println("ship shot"); hitResponse(response); } if (response.startsWith("shipSuccessfullyPlaced")) { shipPlacedResponse(response); } if (response.startsWith("destroyed")) { destroyedResponse(response); } if (response.equals("endGame")) { closeDown(); } if (response.startsWith("allShipsDestroyed")) allShipsDestroyed(response); response = null; } catch (IOException e) { e.printStackTrace(); } } } }