⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 networkserver.java

📁 用java开发的一个实施策略游戏源码 值得学习一下
💻 JAVA
字号:
/*
	Netwar
	Copyright (C) 2002  Daniel Grund, Kyle Kakligian, Jason Komutrattananon, & Brian Hibler.

	This file is part of Netwar.

	Netwar is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	Netwar is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Netwar; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package netwar.network;
import netwar.game.Command;
import netwar.settings.*;
import java.rmi.*;
import java.rmi.server.*;

/**
 * NetworkServer. The central server object that takes commands from players (local or remote) and broadcasts them to all players.
 * @author Group N2-Project Netwar
 * @author Jason Komutrattananon
 */
public class NetworkServer extends UnicastRemoteObject implements NetworkServerInterface{
	private int totalPlayerCount, remoteCommandsRecieved;
	private NetworkClientInterface networkInterfaceForPlayer[];
	private Command collectedCommands[];
	private final int maxPlayers = 12;
	private boolean[] whoIsStillInGame = new boolean[maxPlayers+1];
	private boolean gameStarted = false;

	/**
	 * Global Server object so server can be referenced on the local "host" machine
	 */
	public static NetworkServer server = null;

	/**
	 * Creates a new instance of NetworkServer which is binded to "NetwarServer" in the RMI Registry.
	 */
	public NetworkServer() throws RemoteException{
		server = this;
		try{
			Naming.rebind("NetwarServer",this);
		} catch (Exception e){
			System.out.println("Exception while trying to start up server: " +e);
		}
		totalPlayerCount = 0;
		// Maximum number of players is set by the size of networkInterfaceForPlayer array
		networkInterfaceForPlayer = new NetworkClientInterface[13];
		try{
		    System.out.println("Your IP address is " + java.net.InetAddress.getLocalHost());
		} catch (Exception e){
		    System.out.println("doh");
		}
	}

	/**
	 * Sends the command the player made to the server
	 * RMI type: Server
	 * @param playerNumber The number of the player that set the command.
	 * @param remotePlayersCommand The command the player made that needs to be broadcast to the server.
	 * @throws RemoteException In the case of not being able to connect or send data to the remote computer.
	 */
	public synchronized void setCommand(int playerNumber, Command remotePlayersCommand) throws RemoteException{
		collectedCommands[playerNumber] = remotePlayersCommand;
		remoteCommandsRecieved++;
		
		if (remoteCommandsRecieved == totalPlayerCount) {
			for (int i = 1; i<=maxPlayers;i++){
			    if(whoIsStillInGame[i]==true){
				networkInterfaceForPlayer[i].setCompleteSetOfCommands(collectedCommands);
			    }
			}
			remoteCommandsRecieved = 0;
		}
	}

	/**
	 * Sends the networkClientInterface to the server so the server can talk back to the client without the host user having to input the ip address of the client or start the RMIRegistry client side
	 * RMI type: Client & Server
	 * @param Client The number of the player that set the command.
	 * @throws RemoteException In the case of not being able to connect or send data to the remote computer.
	 */
	public synchronized int callerID(NetworkClientInterface client) throws RemoteException{
		networkInterfaceForPlayer[++totalPlayerCount] = client;
		whoIsStillInGame[totalPlayerCount] = true;	    // The server now knows this player is in the game, useful in case a player wants to drop out mid-game.
		collectedCommands = new Command[totalPlayerCount + 1];
		return totalPlayerCount;
	}

	/**
	 * Sends the signal to start the game to every client.
	 * RMI type: Client
	 */
	public void startGame() {
		try {
			for (int i = 1; i <= totalPlayerCount; i++) {
				networkInterfaceForPlayer[i].startGame();
				gameStarted = true;
			}
		} catch (Exception e){
			System.out.println("Start Game Remote Exception: " + e);
		}
	}
            
	/**
	 * Sends the settings the player made to the server.
	 * RMI type: Client & Server
	 * @param callingPlayer The number of the player that called the method.
	 * @param playerSettings The player's settings that will be sent to the server.
	 * @param GlobalSettings The global settings that will be sent to the server.
	 * @throws RemoteException In the case of not being able to connect or send data to the remote computer.
	 */
	public synchronized void broadcastSettings(int callingPlayer, PlayerSettings playerSettings, GlobalSettings globalSettings) throws RemoteException{
		GameSettings.currentSettings.reviseSettings(callingPlayer, playerSettings, globalSettings);		// Integrates the changes to settings on player 1's computer
		for (int i = 2; i <= totalPlayerCount; i++) {							// Broadcasts the settings to all player except for player 1
			try{
				networkInterfaceForPlayer[i].clientRecieveSettings(GameSettings.currentSettings);
			} catch (Exception e) {
				System.out.println("Remote Exception while trying to broadcast settings from server to clients " + e );
			}
		}
	}
	
	/**
	 * Sends the chat message to its intended target.
	 * RMI type: Client & Server
	 * @param chatMessage The message to be sent
	 * @param toWhom who to send it to
	 */
	public synchronized void sendChat(String chatMessage, boolean[] toWhom, int fromWhom) throws RemoteException{
		if (toWhom[0]==true){
			// broadcast message to all players
			for (int i = 1; i<=totalPlayerCount; i++){
				try{
					networkInterfaceForPlayer[i].displayChat(
										    GameSettings.currentSettings.players[fromWhom-1].teamName
										    + ": " 
										    + chatMessage
					);
				}catch (Exception e) {
					System.out.println("Exception while trying to broadcast message from server to clients: " + e);
				}
			}
		}
		else{
			//check which players get the message
			for (int i = 1; i<=totalPlayerCount; i++){
				if (toWhom[i]==true){
				    // broadcast message to player i
					try {
					    networkInterfaceForPlayer[i].displayChat(
						GameSettings.currentSettings.players[fromWhom-1].teamName	//the player's name
						+ ": "
						+ chatMessage							// the chat messege
					    );
					}catch (Exception e) {
						System.out.println("Exception while trying to broadcast message to player " + i + ": " + e);
					}
				}
			}
		}
	}
	
	/**
	 * Let's the server know a player has dropped out of a game. If the game has not started, it opens the slot up for another player to join in
	 * @param thisPlayersNumber Player # of who dropped out
	 * @return true server acknowledges request.
	 */
	public synchronized boolean dropMeFromGame(int thisPlayersNumber) throws RemoteException{
		if(gameStarted==true){	//if the game is started set player's flag to dropped Player's spot is not freed because in the middle of a game.
			whoIsStillInGame[thisPlayersNumber]=false;
			totalPlayerCount--;
			for(int i = 1; i<=maxPlayers; i++){
				try {
					if(whoIsStillInGame[i]==true){
						networkInterfaceForPlayer[i].displayChat(GameSettings.currentSettings.players[thisPlayersNumber-1].teamName + " has quit from the game");
					}
				}catch (Exception e) {
					System.out.println("Exception while trying to drop player: " + e);
				}
			}
		    return true;
		}
		else {			//if the game has not started drop player and free player's spot.
			totalPlayerCount--;
			for (int i = thisPlayersNumber; i<totalPlayerCount+1; i++){
				if (i != maxPlayers){
					networkInterfaceForPlayer[i] = networkInterfaceForPlayer[i+1];
					if(networkInterfaceForPlayer[i]!=null){
						try {
							networkInterfaceForPlayer[i].setPlayerNumber(i);	//Tell the player his number has changed.
						} catch (Exception e) {
							System.out.println("Exception while trying to drop player before game started");
						}
					}
				} else {
					networkInterfaceForPlayer[i] = null;
				}
			}
			return true;
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -