soc.server
Class SOCServer

java.lang.Object
  extended byjava.lang.Thread
      extended bysoc.server.genericServer.Server
          extended bysoc.server.SOCServer
All Implemented Interfaces:
java.lang.Cloneable, java.lang.Runnable, java.io.Serializable

public class SOCServer
extends Server

A server for Settlers of Catan

Author:
Robert S. Thomas Note: This is an attempt at being more modular. 5/13/99 RST Note: Hopfully fixed all of the deadlock problems. 12/27/01 RST
See Also:
Serialized Form

Nested Class Summary
 
Nested classes inherited from class soc.server.genericServer.Server
Server.NetStringServerSocket
 
Field Summary
protected  SOCChannelList channelList
          list of chat channels
static int CLI_VERSION_MIN
          Minimum required client version, to connect and play a game.
static java.lang.String CLI_VERSION_MIN_DISPLAY
          Minimum required client version, in "display" form, like "1.0.00".
(package private)  java.lang.String databasePassword
           
(package private)  java.lang.String databaseUserName
           
static int GAME_EXPIRE_WARN_MINUTES
          If game will expire in this or fewer minutes, warn the players.
protected  java.util.Hashtable gameDataFiles
          table of game data files
protected  SOCGameList gameList
          list of soc games
(package private)  SOCGameTimeoutChecker gameTimeoutChecker
          game timeout checker
protected  int maxConnections
          Maximum number of connections allowed
static java.lang.String MSG_NICKNAME_ALREADY_IN_USE
          Status Message to send, nickname already logged into the system
protected  int numberOfGamesFinished
          the total number of games finished
protected  int numberOfGamesStarted
          the total number of games that have been started
protected  int numberOfUsers
          total number of users
 int port
          The TCP port we listen on.
static java.lang.String PRACTICE_STRINGPORT
          For local practice games (pipes, not TCP), the name of the pipe.
private  java.util.Random rand
          So we can get random numbers.
static SOCRobotParameters ROBOT_PARAMS_DEFAULT
          Robot default parameters; copied for each newly connecting robot.
static SOCRobotParameters ROBOT_PARAMS_SMARTER
          Smarter robot default parameters.
protected  java.util.Hashtable robotDismissRequests
          table of requestst for robots to leave games
protected  java.util.Hashtable robotJoinRequests
          table of requests for robots to join games
protected  java.util.Vector robots
          A list of robots connected to this server
static java.lang.String SERVERNAME
          Name used when sending messages from the server.
(package private)  SOCServerRobotPinger serverRobotPinger
          server robot pinger
protected  long startTime
          the time that this server was started
 
Fields inherited from class soc.server.genericServer.Server
conns, error, inQueue, numberOfConnections, strSocketName, unnamedConns
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
SOCServer(int p, int mc, java.lang.String databaseUserName, java.lang.String databasePassword)
          Create a Settlers of Catan server listening on port p.
SOCServer(java.lang.String s, int mc, java.lang.String databaseUserName, java.lang.String databasePassword)
          Create a Settlers of Catan server listening on local stringport s.
 
Method Summary
private  boolean authenticateUser(StringConnection c, java.lang.String userName, java.lang.String password)
          authenticate the user see if the user is in the db, if so then check the password if they're not in the db, but they supplied a password then send a message if they're not in the db, and no password, then ok
protected  void broadcastGameStats(SOCGame ga)
          this broadcasts game information to all people connected used to display the scores on the player client
 void checkForExpiredGames()
          check for games that have expired and destroy them.
private  boolean checkNickname(java.lang.String n)
          check if a name is ok a name is ok if it hasn't been used yet
protected  boolean checkTurn(StringConnection c, SOCGame ga)
          make sure it's the player's turn
 void connectToChannel(StringConnection c, java.lang.String ch)
          Adds a connection to a chat channel.
 boolean connectToGame(StringConnection c, java.lang.String ga)
          Adds a connection to a game.
private  void createNewGameEventRecord()
          create a new game event record
 void destroyGame(java.lang.String gm)
          destroy the game WARNING: MUST HAVE THE gameList.takeMonitor() before calling this method
private  void endGameTurn(SOCGame ga)
          Pre-checking already done, end the current player's turn in this game.
private  void forceEndGameTurn(SOCGame ga, java.lang.String plName)
          Try to force-end the current player's turn in this game.
private  void forceGamePlayerDiscard(SOCGame cg, int cpn, StringConnection c, java.lang.String plName, int pn)
          Force this player (not current player) to discard, and report resources to all players.
private  SOCBoardLayout getBoardLayoutMessage(SOCGame ga)
          put together the SOCBoardLayout message
 java.util.Enumeration getGameNames()
          Used when SOCPlayerClient is also hosting games.
 int getGameState(java.lang.String gm)
          Given a game name on this server, return its state.
protected  void giveDevCard(java.lang.String mes, SOCGame game)
          this is a debugging command that gives a dev card to a player
protected  void giveResources(java.lang.String mes, SOCGame game)
          this is a debugging command that gives resources to a player
private  void handleACCEPTOFFER(StringConnection c, SOCAcceptOffer mes)
          handle "accept offer" message
private  void handleBANKTRADE(StringConnection c, SOCBankTrade mes)
          handle "bank trade" message
private  void handleBUILDREQUEST(StringConnection c, SOCBuildRequest mes)
          handle "build request" message
private  void handleBUYCARDREQUEST(StringConnection c, SOCBuyCardRequest mes)
          handle "buy card request" message
private  void handleCANCELBUILDREQUEST(StringConnection c, SOCCancelBuildRequest mes)
          handle "cancel build request" message
private  void handleCHANGEFACE(StringConnection c, SOCChangeFace mes)
          handle "change face" message
private  void handleCHOOSEPLAYER(StringConnection c, SOCChoosePlayer mes)
          handle "choose player" message during robbery
private  void handleCLEAROFFER(StringConnection c, SOCClearOffer mes)
          handle "clear offer" message
private  void handleCREATEACCOUNT(StringConnection c, SOCCreateAccount mes)
          handle "create account" message
private  void handleDISCARD(StringConnection c, SOCDiscard mes)
          handle "discard" message
private  void handleDISCOVERYPICK(StringConnection c, SOCDiscoveryPick mes)
          handle "discovery pick" message (while playing Discovery card)
private  void handleENDTURN(StringConnection c, SOCEndTurn mes)
          handle "end turn" message
private  void handleIMAROBOT(StringConnection c, SOCImARobot mes)
          Handle the "I'm a robot" message.
private  void handleJOIN(StringConnection c, SOCJoin mes)
          Handle the "join a channel" message.
private  void handleJOINGAME(StringConnection c, SOCJoinGame mes)
          Handle the "join a game" message: Join or create a game.
private  void handleLEAVE(StringConnection c, SOCLeave mes)
          Handle the "leave a channel" message
private  void handleLEAVEGAME(StringConnection c, SOCLeaveGame mes)
          Handle the "leave game" message
private  void handleMAKEOFFER(StringConnection c, SOCMakeOffer mes)
          handle "make offer" message
private  void handleMONOPOLYPICK(StringConnection c, SOCMonopolyPick mes)
          handle "monopoly pick" message
private  void handleMOVEROBBER(StringConnection c, SOCMoveRobber mes)
          handle "move robber" message
private  void handlePLAYDEVCARDREQUEST(StringConnection c, SOCPlayDevCardRequest mes)
          handle "play development card request" message
private  void handlePUTPIECE(StringConnection c, SOCPutPiece mes)
          handle "put piece" message
private  void handleREJECTOFFER(StringConnection c, SOCRejectOffer mes)
          handle "reject offer" message
private  void handleRESETBOARDREQUEST(StringConnection c, SOCResetBoardRequest mes)
          handle "reset-board request" message.
private  void handleRESETBOARDVOTE(StringConnection c, SOCResetBoardVote mes)
          handle message of player's vote for a "reset-board" request.
private  void handleROLLDICE(StringConnection c, SOCRollDice mes)
          handle "roll dice" message
private  void handleSETSEATLOCK(StringConnection c, SOCSetSeatLock mes)
          handle "set seat lock" message
private  void handleSITDOWN(StringConnection c, SOCSitDown mes)
          handle "sit down" message
private  void handleSTARTGAME(StringConnection c, SOCStartGame mes)
          handle "start game" message.
private  void handleVERSION(StringConnection c, SOCVersion mes)
          Handle the "version" message, client's version report.
private  void initSocServer(java.lang.String databaseUserName, java.lang.String databasePassword)
          Common init for both constructors.
private  void joinGame(SOCGame gameData, StringConnection c, boolean isReset)
          Client has been approved to join game; send the entire state of the game to client, send client join event to other players.
 java.util.Vector leaveAllChannels(StringConnection c)
          the connection c leaves all channels it was in
 java.util.Vector leaveAllGames(StringConnection c)
          the connection c leaves all games it was in
 boolean leaveChannel(StringConnection c, java.lang.String ch, boolean channelListLock)
          the connection c leaves the channel ch WARNING: MUST HAVE THE channelList.takeMonitorForChannel(ch) before calling this method
 void leaveConnection(StringConnection c)
          things to do when the connection c leaves
 boolean leaveGame(StringConnection c, java.lang.String gm, boolean gameListLock)
          the connection c leaves the game gm.
static void main(java.lang.String[] args)
          Starting the server from the command line
 void messageToChannel(java.lang.String ch, SOCMessage mes)
          Send a message to the given channel
 void messageToChannelWithMon(java.lang.String ch, SOCMessage mes)
          Send a message to the given channel WARNING: MUST HAVE THE gameList.takeMonitorForChannel(ch) before calling this method
 void messageToGame(java.lang.String ga, SOCMessage mes)
          Send a message to the given game
 void messageToGameExcept(java.lang.String gn, StringConnection ex, SOCMessage mes)
          Send a message to all the connections in a game excluding one.
 void messageToGameExcept(java.lang.String gn, java.util.Vector ex, SOCMessage mes)
          Send a message to all the connections in a game excluding some.
 void messageToGameUrgent(java.lang.String ga, java.lang.String mes)
          Send an urgent SOCGameTextMsg to the given game.
 void messageToGameWithMon(java.lang.String ga, SOCMessage mes)
          Send a message to the given game WARNING: MUST HAVE THE gameList.takeMonitorForGame(ga) before calling this method
 void messageToPlayer(StringConnection c, SOCMessage mes)
          Send a message to a player and record it
 boolean newConnection1(StringConnection c)
          Things to do when a new connection comes.
protected  void newConnection2(StringConnection c)
          Send welcome messages (server version, and the lists of channels and games (SOCChannels, SOCGames)) when a new connection comes, part 2 - c has been accepted and added to a connection list.
 void processCommand(java.lang.String s, StringConnection c)
          Treat the incoming messages.
 void processDebugCommand(StringConnection debugCli, java.lang.String ga, java.lang.String dcmd)
          Process a debug command, sent by the "debug" client/player.
private  void readyGameAskRobotsJoin(SOCGame ga, StringConnection[] robotSeats)
          Fill all the unlocked empty seats with robots.
protected  void recordGameEvent(java.lang.String gameName, java.lang.String event)
          record events that happen during the game
protected  void reportBankTrade(SOCGame ga, SOCResourceSet give, SOCResourceSet get)
          report that the current player traded with the bank or a port, using SOCPlayerElement and SOCGameTextMsg messages.
protected  void reportRobbery(SOCGame ga, SOCPlayer pe, SOCPlayer vi, int rsrc)
          The current player is stealing from another player.
private  void reportRsrcGainLoss(java.lang.String gaName, SOCResourceSet rset, boolean isLoss, int mainPlayer, int tradingPlayer, java.lang.StringBuffer message, StringConnection playerConn)
          Report the resources gained/lost by a player, and optionally (for trading) lost/gained by a second player.
protected  void reportTrade(SOCGame ga, int offering, int accepting)
          report a trade that has taken place between players, using SOCPlayerElement and SOCGameTextMsg messages.
private  void resetBoardAndNotify(java.lang.String gaName, int requestingPlayer)
          Reset the board, to a copy with same players but new layout.
private  void saveCurrentGameEventRecord(java.lang.String gn)
          save the current game event record in the game record
protected  void sendGameState(SOCGame ga)
          send the current state of the game with a message.
protected  boolean sendGameState(SOCGame ga, boolean sendRollPrompt)
          send the current state of the game with a message.
protected  void sendGameStateOVER(SOCGame ga)
          If game is OVER, send messages reporting winner, final score, and each player's victory-point cards.
private  void sendTurn(SOCGame ga, boolean sendRollPrompt)
          send whose turn it is.
private  boolean setClientVersionOrReject(StringConnection c, int cvers)
          Set client's version, and check against minimum required version CLI_VERSION_MIN.
private  void sitDown(SOCGame ga, StringConnection c, int pn, boolean robot, boolean isReset)
          This player is sitting down at the game
protected  void startGame(SOCGame ga)
          do the stuff you need to do to start a game
 void stopServer()
          The server is being cleanly stopped.
 void stopServer(java.lang.String stopMsg)
          The server is being cleanly stopped.
protected  void storeGameScores(SOCGame ga)
          if all the players stayed for the whole game, record the scores in the database
 
Methods inherited from class soc.server.genericServer.Server
addConnection, broadcast, connectionCount, getConnection, getConnections, isUp, nameConnection, removeConnection, removeConnectionCleanup, run, serverDown, treat
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

SERVERNAME

public static final java.lang.String SERVERNAME
Name used when sending messages from the server.

See Also:
Constant Field Values

CLI_VERSION_MIN

public static final int CLI_VERSION_MIN
Minimum required client version, to connect and play a game. Same format as Version.versionNumber(). Currently there is no minimum.

See Also:
setClientVersionOrReject(StringConnection, int), Constant Field Values

CLI_VERSION_MIN_DISPLAY

public static final java.lang.String CLI_VERSION_MIN_DISPLAY
Minimum required client version, in "display" form, like "1.0.00". Currently there is no minimum.

See Also:
setClientVersionOrReject(StringConnection, int), Constant Field Values

GAME_EXPIRE_WARN_MINUTES

public static int GAME_EXPIRE_WARN_MINUTES
If game will expire in this or fewer minutes, warn the players. Default 10. Must be at least twice the sleep-time in SOCGameTimeoutChecker.run(). The game expiry time is set at game creation in SOCGameList.CreateGame.

See Also:
checkForExpiredGames(), SOCGameTimeoutChecker.run(), SOCGameList.createGame(String)

PRACTICE_STRINGPORT

public static java.lang.String PRACTICE_STRINGPORT
For local practice games (pipes, not TCP), the name of the pipe. Used to distinguish practice vs "real" games.

See Also:
LocalStringConnection

rand

private java.util.Random rand
So we can get random numbers.


port

public int port
The TCP port we listen on.


maxConnections

protected int maxConnections
Maximum number of connections allowed


robots

protected java.util.Vector robots
A list of robots connected to this server


ROBOT_PARAMS_DEFAULT

public static SOCRobotParameters ROBOT_PARAMS_DEFAULT
Robot default parameters; copied for each newly connecting robot. Changing this will not change parameters of any robots already connected.

See Also:
handleIMAROBOT(StringConnection, soc.message.SOCImARobot), SOCRobotDM

ROBOT_PARAMS_SMARTER

public static SOCRobotParameters ROBOT_PARAMS_SMARTER
Smarter robot default parameters. (For practice games; not referenced by server) Same as ROBOT_PARAMS_DEFAULT but with SMART_STRATEGY, not FAST_STRATEGY.

See Also:
ROBOT_PARAMS_DEFAULT, SOCRobotDM

MSG_NICKNAME_ALREADY_IN_USE

public static final java.lang.String MSG_NICKNAME_ALREADY_IN_USE
Status Message to send, nickname already logged into the system

See Also:
Constant Field Values

channelList

protected SOCChannelList channelList
list of chat channels


gameList

protected SOCGameList gameList
list of soc games


robotJoinRequests

protected java.util.Hashtable robotJoinRequests
table of requests for robots to join games


robotDismissRequests

protected java.util.Hashtable robotDismissRequests
table of requestst for robots to leave games


gameDataFiles

protected java.util.Hashtable gameDataFiles
table of game data files


startTime

protected long startTime
the time that this server was started


numberOfGamesStarted

protected int numberOfGamesStarted
the total number of games that have been started


numberOfGamesFinished

protected int numberOfGamesFinished
the total number of games finished


numberOfUsers

protected int numberOfUsers
total number of users


serverRobotPinger

SOCServerRobotPinger serverRobotPinger
server robot pinger


gameTimeoutChecker

SOCGameTimeoutChecker gameTimeoutChecker
game timeout checker


databaseUserName

java.lang.String databaseUserName

databasePassword

java.lang.String databasePassword
Constructor Detail

SOCServer

public SOCServer(int p,
                 int mc,
                 java.lang.String databaseUserName,
                 java.lang.String databasePassword)
Create a Settlers of Catan server listening on port p. You must start its thread yourself.

Parameters:
p - the port that the server listens on
mc - the maximum number of connections allowed
databaseUserName - the user name for accessing the database
databasePassword - the password for the user

SOCServer

public SOCServer(java.lang.String s,
                 int mc,
                 java.lang.String databaseUserName,
                 java.lang.String databasePassword)
Create a Settlers of Catan server listening on local stringport s. You must start its thread yourself.

Parameters:
s - the stringport that the server listens on
mc - the maximum number of connections allowed
databaseUserName - the user name for accessing the database
databasePassword - the password for the user
Method Detail

initSocServer

private void initSocServer(java.lang.String databaseUserName,
                           java.lang.String databasePassword)
Common init for both constructors.

Parameters:
databaseUserName - Used for DB connect - not retained
databasePassword - Used for DB connect - not retained

connectToChannel

public void connectToChannel(StringConnection c,
                             java.lang.String ch)
Adds a connection to a chat channel. WARNING: MUST HAVE THE channelList.takeMonitorForChannel(ch) before calling this method

Parameters:
c - the Connection to be added
ch - the name of the channel

leaveChannel

public boolean leaveChannel(StringConnection c,
                            java.lang.String ch,
                            boolean channelListLock)
the connection c leaves the channel ch WARNING: MUST HAVE THE channelList.takeMonitorForChannel(ch) before calling this method

Parameters:
c - the connection
ch - the channel
channelListLock - true if we have the channelList monitor
Returns:
true if we destroyed the channel

connectToGame

public boolean connectToGame(StringConnection c,
                             java.lang.String ga)
Adds a connection to a game. If the game doesn't yet exist, create it.

Parameters:
c - the Connection to be added; its name and version should already be set.
ga - the name of the game
Returns:
true if c was not a member of ch before

leaveGame

public boolean leaveGame(StringConnection c,
                         java.lang.String gm,
                         boolean gameListLock)
the connection c leaves the game gm.

WARNING: MUST HAVE THE gameList.takeMonitorForGame(gm) before calling this method

Parameters:
c - the connection; if c is being dropped because of an error, this method assumes that StringConnection.disconnect() has already been called. This method won't exclude c from any communication about leaving the game, in case they are still connected and in other games.
gm - the game
gameListLock - true if we have the gameList.takeMonitor() lock
Returns:
true if the game was destroyed (because c was the last non-robot player, and no one was watching)

forceGamePlayerDiscard

private void forceGamePlayerDiscard(SOCGame cg,
                                    int cpn,
                                    StringConnection c,
                                    java.lang.String plName,
                                    int pn)
Force this player (not current player) to discard, and report resources to all players. Does not send gameState, which may have changed; see SOCGame.discardPickRandom(SOCResourceSet, int, SOCResourceSet, Random).

Assumes, as endGameTurn(SOCGame) does:

Parameters:
cg - Game object
cpn - Game's current player number
c - Connection of discarding player
plName - Discarding player's name, for GameTextMsg
pn - Player number who must discard

destroyGame

public void destroyGame(java.lang.String gm)
destroy the game WARNING: MUST HAVE THE gameList.takeMonitor() before calling this method

Parameters:
gm - the name of the game

getGameNames

public java.util.Enumeration getGameNames()
Used when SOCPlayerClient is also hosting games.

Returns:
The names (Strings) of games on this server

getGameState

public int getGameState(java.lang.String gm)
Given a game name on this server, return its state.

Parameters:
gm - Game name
Returns:
Game's state, or -1 if no game with that name on this server

leaveAllChannels

public java.util.Vector leaveAllChannels(StringConnection c)
the connection c leaves all channels it was in

Parameters:
c - the connection
Returns:
the channels it was in

leaveAllGames

public java.util.Vector leaveAllGames(StringConnection c)
the connection c leaves all games it was in

Parameters:
c - the connection
Returns:
the games it was in

messageToChannel

public void messageToChannel(java.lang.String ch,
                             SOCMessage mes)
Send a message to the given channel

Parameters:
ch - the name of the channel
mes - the message to send

messageToChannelWithMon

public void messageToChannelWithMon(java.lang.String ch,
                                    SOCMessage mes)
Send a message to the given channel WARNING: MUST HAVE THE gameList.takeMonitorForChannel(ch) before calling this method

Parameters:
ch - the name of the channel
mes - the message to send

messageToPlayer

public void messageToPlayer(StringConnection c,
                            SOCMessage mes)
Send a message to a player and record it

Parameters:
c - the player connection
mes - the message to send

messageToGame

public void messageToGame(java.lang.String ga,
                          SOCMessage mes)
Send a message to the given game

Parameters:
ga - the name of the game
mes - the message to send. If mes is a SOCGameTextMsg whose text begins with ">>>", the client should consider this an urgent message, and draw the user's attention in some way. (See messageToGameUrgent(String, String))

messageToGameWithMon

public void messageToGameWithMon(java.lang.String ga,
                                 SOCMessage mes)
Send a message to the given game WARNING: MUST HAVE THE gameList.takeMonitorForGame(ga) before calling this method

Parameters:
ga - the name of the game
mes - the message to send

messageToGameExcept

public void messageToGameExcept(java.lang.String gn,
                                java.util.Vector ex,
                                SOCMessage mes)
Send a message to all the connections in a game excluding some.

Parameters:
gn - the name of the game
ex - the list of exceptions
mes - the message

messageToGameExcept

public void messageToGameExcept(java.lang.String gn,
                                StringConnection ex,
                                SOCMessage mes)
Send a message to all the connections in a game excluding one.

Parameters:
gn - the name of the game
ex - the excluded connection, or null
mes - the message

messageToGameUrgent

public void messageToGameUrgent(java.lang.String ga,
                                java.lang.String mes)
Send an urgent SOCGameTextMsg to the given game. An "urgent" message is a SOCGameTextMsg whose text begins with ">>>"; the client should draw the user's attention in some way.

Like messageToGame, will take and release the game's monitor.

Parameters:
ga - the name of the game
mes - the message to send. If mes does not begin with ">>>", will prepend ">>> " before sending mes.

leaveConnection

public void leaveConnection(StringConnection c)
things to do when the connection c leaves

Overrides:
leaveConnection in class Server
Parameters:
c - the connection

newConnection1

public boolean newConnection1(StringConnection c)
Things to do when a new connection comes. If the connection is accepted, it's added to Server.unnamedConns until the player "names" it by joining or creating a game under their player name. Other communication is then done, in newConnection2(StringConnection). SYNCHRONIZATION NOTE: During the call to newConnection1, the monitor lock of Server.unnamedConns is held. Thus, defer as much as possible until newConnection2(StringConnection) (after the connection is accepted).

Overrides:
newConnection1 in class Server
Parameters:
c - the new Connection
Returns:
true to accept and continue, false if you have rejected this connection; if false, addConnection will call StringConnection.disconnectSoft().
See Also:
Server.addConnection(StringConnection), newConnection2(StringConnection), Server.nameConnection(StringConnection)

newConnection2

protected void newConnection2(StringConnection c)
Send welcome messages (server version, and the lists of channels and games (SOCChannels, SOCGames)) when a new connection comes, part 2 - c has been accepted and added to a connection list. Unlike newConnection1(StringConnection), no connection-list locks are held when this method is called.

Also set client's "assumed version" to -1, until we have sent and received a VERSION message.

Overrides:
newConnection2 in class Server

checkNickname

private boolean checkNickname(java.lang.String n)
check if a name is ok a name is ok if it hasn't been used yet

Parameters:
n - the name
Returns:
true if the name is ok

processCommand

public void processCommand(java.lang.String s,
                           StringConnection c)
Treat the incoming messages. Messages of unknown type are ignored.

Note: When there is a choice, always use local information over information from the message. For example, use the nickname from the connection to get the player information rather than the player information from the message. This makes it harder to send false messages making players do things they didn't want to do.

Specified by:
processCommand in class Server
Parameters:
s - String containing the message
c - the Connection that sent the Message

processDebugCommand

public void processDebugCommand(StringConnection debugCli,
                                java.lang.String ga,
                                java.lang.String dcmd)
Process a debug command, sent by the "debug" client/player.


stopServer

public void stopServer()
The server is being cleanly stopped. Shut down with a final message "The game server is shutting down".

Overrides:
stopServer in class Server

stopServer

public void stopServer(java.lang.String stopMsg)
The server is being cleanly stopped. Send a final message, disconnect all the connections, disconnect from database if connected. Currently called only by the debug command "*STOP*", and by SOCPlayerClient's locally hosted TCP server.

Parameters:
stopMsg - Final text message to send to all connected clients, or null. Will be sent as a SOCBCastTextMsg. As always, if message starts with ">>" it will be considered urgent.

authenticateUser

private boolean authenticateUser(StringConnection c,
                                 java.lang.String userName,
                                 java.lang.String password)
authenticate the user see if the user is in the db, if so then check the password if they're not in the db, but they supplied a password then send a message if they're not in the db, and no password, then ok

Parameters:
c - the user's connection
userName - the user's nickname
password - the user's password
Returns:
true if the user has been authenticated

handleVERSION

private void handleVERSION(StringConnection c,
                           SOCVersion mes)
Handle the "version" message, client's version report. May ask to disconnect, if version is too old.

Parameters:
c - the connection that sent the message
mes - the messsage

setClientVersionOrReject

private boolean setClientVersionOrReject(StringConnection c,
                                         int cvers)
Set client's version, and check against minimum required version CLI_VERSION_MIN. If version is too low, send SOCRejectConnection.

Parameters:
c - Client's connection
cvers - Version reported by client, or assumed if no report
Returns:
True if OK, false if rejected

handleJOIN

private void handleJOIN(StringConnection c,
                        SOCJoin mes)
Handle the "join a channel" message. If client hasn't yet sent its version, assume is version 1.0.00, disconnect if too low.

Parameters:
c - the connection that sent the message
mes - the messsage

handleLEAVE

private void handleLEAVE(StringConnection c,
                         SOCLeave mes)
Handle the "leave a channel" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleIMAROBOT

private void handleIMAROBOT(StringConnection c,
                            SOCImARobot mes)
Handle the "I'm a robot" message. Robots send their SOCVersion before sending this message. Their version is checked here, must equal server's version.

Parameters:
c - the connection that sent the message
mes - the messsage

handleJOINGAME

private void handleJOINGAME(StringConnection c,
                            SOCJoinGame mes)
Handle the "join a game" message: Join or create a game. Will join the game, or return a STATUSMESSAGE if nickname is not OK. If client hasn't yet sent its version, assume is version 1.0.00, disconnect if too low.

Parameters:
c - the connection that sent the message
mes - the messsage

handleLEAVEGAME

private void handleLEAVEGAME(StringConnection c,
                             SOCLeaveGame mes)
Handle the "leave game" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleSITDOWN

private void handleSITDOWN(StringConnection c,
                           SOCSitDown mes)
handle "sit down" message

Parameters:
c - the connection that sent the message
mes - the messsage

handlePUTPIECE

private void handlePUTPIECE(StringConnection c,
                            SOCPutPiece mes)
handle "put piece" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleMOVEROBBER

private void handleMOVEROBBER(StringConnection c,
                              SOCMoveRobber mes)
handle "move robber" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleSTARTGAME

private void handleSTARTGAME(StringConnection c,
                             SOCStartGame mes)
handle "start game" message. Game state must be NEW, or this message is ignored.

Parameters:
c - the connection that sent the message
mes - the messsage

readyGameAskRobotsJoin

private void readyGameAskRobotsJoin(SOCGame ga,
                                    StringConnection[] robotSeats)
                             throws java.lang.IllegalStateException,
                                    java.lang.IllegalArgumentException
Fill all the unlocked empty seats with robots. Builds a Vector of StringConnections of robots asked to join, and adds it to the robotJoinRequests table. Game state should be READY. Called by handleSTARTGAME, resetBoardAndNotify. MUST be called ONLY from the one thread handling all inbound messages, or (race condition) the robots may ask to join before we've set up robotJoinRequests.

Parameters:
ga - Game to ask robots to join
robotSeats - If robotSeats is null, robots are randomly selected. If non-null, a MAXPLAYERS-sized array of StringConnections. Any vacant non-locked seat, with index i, is filled with the robot whose connection is robotSeats[i]. Other indexes should be null, and won't be used.
Throws:
java.lang.IllegalStateException - if ga.gamestate is not READY
java.lang.IllegalArgumentException - if robotSeats is not null but wrong length, or if a robotSeat element is null but that seat wants a robot (vacant non-locked).

handleROLLDICE

private void handleROLLDICE(StringConnection c,
                            SOCRollDice mes)
handle "roll dice" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleDISCARD

private void handleDISCARD(StringConnection c,
                           SOCDiscard mes)
handle "discard" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleENDTURN

private void handleENDTURN(StringConnection c,
                           SOCEndTurn mes)
handle "end turn" message

Parameters:
c - the connection that sent the message
mes - the messsage

endGameTurn

private void endGameTurn(SOCGame ga)
Pre-checking already done, end the current player's turn in this game. Alter game state and send messages to players.

Assumes:

Parameters:
ga - Game to end turn

forceEndGameTurn

private void forceEndGameTurn(SOCGame ga,
                              java.lang.String plName)
Try to force-end the current player's turn in this game. Alter game state and send messages to players. Will call endGameTurn(SOCGame) if appropriate. Will send gameState and current player (turn) to clients.

Assumes, as endGameTurn(SOCGame) does:

Parameters:
ga - Game to force end turn
plName - Current player's name. Needed because if they have been disconnected by leaveGame(StringConnection, String, boolean), their name within game object is already null.
See Also:
SOCGame.forceEndTurn()

handleCHOOSEPLAYER

private void handleCHOOSEPLAYER(StringConnection c,
                                SOCChoosePlayer mes)
handle "choose player" message during robbery

Parameters:
c - the connection that sent the message
mes - the messsage

handleMAKEOFFER

private void handleMAKEOFFER(StringConnection c,
                             SOCMakeOffer mes)
handle "make offer" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleCLEAROFFER

private void handleCLEAROFFER(StringConnection c,
                              SOCClearOffer mes)
handle "clear offer" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleREJECTOFFER

private void handleREJECTOFFER(StringConnection c,
                               SOCRejectOffer mes)
handle "reject offer" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleACCEPTOFFER

private void handleACCEPTOFFER(StringConnection c,
                               SOCAcceptOffer mes)
handle "accept offer" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleBANKTRADE

private void handleBANKTRADE(StringConnection c,
                             SOCBankTrade mes)
handle "bank trade" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleBUILDREQUEST

private void handleBUILDREQUEST(StringConnection c,
                                SOCBuildRequest mes)
handle "build request" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleCANCELBUILDREQUEST

private void handleCANCELBUILDREQUEST(StringConnection c,
                                      SOCCancelBuildRequest mes)
handle "cancel build request" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleBUYCARDREQUEST

private void handleBUYCARDREQUEST(StringConnection c,
                                  SOCBuyCardRequest mes)
handle "buy card request" message

Parameters:
c - the connection that sent the message
mes - the messsage

handlePLAYDEVCARDREQUEST

private void handlePLAYDEVCARDREQUEST(StringConnection c,
                                      SOCPlayDevCardRequest mes)
handle "play development card request" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleDISCOVERYPICK

private void handleDISCOVERYPICK(StringConnection c,
                                 SOCDiscoveryPick mes)
handle "discovery pick" message (while playing Discovery card)

Parameters:
c - the connection that sent the message
mes - the messsage

handleMONOPOLYPICK

private void handleMONOPOLYPICK(StringConnection c,
                                SOCMonopolyPick mes)
handle "monopoly pick" message

Parameters:
c - the connection that sent the message
mes - the messsage

handleCHANGEFACE

private void handleCHANGEFACE(StringConnection c,
                              SOCChangeFace mes)
handle "change face" message

Parameters:
c - the connection
mes - the message

handleSETSEATLOCK

private void handleSETSEATLOCK(StringConnection c,
                               SOCSetSeatLock mes)
handle "set seat lock" message

Parameters:
c - the connection
mes - the message

handleRESETBOARDREQUEST

private void handleRESETBOARDREQUEST(StringConnection c,
                                     SOCResetBoardRequest mes)
handle "reset-board request" message. If multiple human players, start a vote. Otherwise, reset the game to a copy with same name and (copy of) same players, new layout.

The requesting player doesn't vote, but server still sends the vote-request-message, to tell that client their request was accepted and voting has begun.

If only one player remains (all other humans have left at end), ask them to start a new game instead. This is a rare occurrence and we shouldn't bring in new robots and all, since we already have an interface to set up a game.

If any human player's client is too old to vote for reset, assume they vote yes.

Parameters:
c - the connection
mes - the message
See Also:
resetBoardAndNotify(String, int)

handleRESETBOARDVOTE

private void handleRESETBOARDVOTE(StringConnection c,
                                  SOCResetBoardVote mes)
handle message of player's vote for a "reset-board" request. Register the player's vote. If all votes have now arrived, and the vote is unanimous, reset the game to a copy with same name and players, new layout.

Parameters:
c - the connection
mes - the message
See Also:
resetBoardAndNotify(String, int)

handleCREATEACCOUNT

private void handleCREATEACCOUNT(StringConnection c,
                                 SOCCreateAccount mes)
handle "create account" message

Parameters:
c - the connection
mes - the message

joinGame

private void joinGame(SOCGame gameData,
                      StringConnection c,
                      boolean isReset)
Client has been approved to join game; send the entire state of the game to client, send client join event to other players. First message sent to connecting client is JOINGAMEAUTH, unless isReset.

Parameters:
gameData - Game to join
c - The connection of joining client
isReset - Game is a board-reset of an existing game

sitDown

private void sitDown(SOCGame ga,
                     StringConnection c,
                     int pn,
                     boolean robot,
                     boolean isReset)
This player is sitting down at the game

Parameters:
ga - the game
c - the connection for the player
pn - which seat the player is taking
robot - true if this player is a robot
isReset - Game is a board-reset of an existing game

reportRobbery

protected void reportRobbery(SOCGame ga,
                             SOCPlayer pe,
                             SOCPlayer vi,
                             int rsrc)
The current player is stealing from another player. Send messages saying what was stolen.

Parameters:
ga - the game
pe - the perpetrator
vi - the the victim
rsrc - type of resource stolen, as in SOCResourceConstants

sendGameState

protected void sendGameState(SOCGame ga)
send the current state of the game with a message. Assumes current player does not change during this state. If we send a text message to prompt the new player to roll, also sends a RollDicePrompt data message. If the client is too old (1.0.6), it will ignore the prompt.

Parameters:
ga - the game
See Also:
sendGameState(SOCGame, boolean)

sendGameState

protected boolean sendGameState(SOCGame ga,
                                boolean sendRollPrompt)
send the current state of the game with a message. Note that the current (or new) player number is not sent here. If game is now OVER, send appropriate messages.

Parameters:
ga - the game
sendRollPrompt - If true, and if we send a text message to prompt the player to roll, send a RollDicePrompt data message. If the client is too old (1.0.6), it will ignore the prompt.
Returns:
did we send a text message to prompt the player to roll? If so, sendTurn can also send a RollDicePrompt data message.
See Also:
sendTurn(SOCGame, boolean), sendGameState(SOCGame), sendGameStateOVER(SOCGame)

sendGameStateOVER

protected void sendGameStateOVER(SOCGame ga)
If game is OVER, send messages reporting winner, final score, and each player's victory-point cards. Also give stats on game length, and on each player's connect time.

Parameters:
ga - This game is over; state should be OVER

reportTrade

protected void reportTrade(SOCGame ga,
                           int offering,
                           int accepting)
report a trade that has taken place between players, using SOCPlayerElement and SOCGameTextMsg messages. Trades are also reported to robots by re-sending the accepting player's SOCAcceptOffer message.

Parameters:
ga - the game
offering - the number of the player making the offer
accepting - the number of the player accepting the offer
See Also:
reportBankTrade(SOCGame, SOCResourceSet, SOCResourceSet)

reportBankTrade

protected void reportBankTrade(SOCGame ga,
                               SOCResourceSet give,
                               SOCResourceSet get)
report that the current player traded with the bank or a port, using SOCPlayerElement and SOCGameTextMsg messages.

Parameters:
ga - the game
give - the number of the player making the offer
get - the number of the player accepting the offer
See Also:
reportTrade(SOCGame, int, int)

reportRsrcGainLoss

private void reportRsrcGainLoss(java.lang.String gaName,
                                SOCResourceSet rset,
                                boolean isLoss,
                                int mainPlayer,
                                int tradingPlayer,
                                java.lang.StringBuffer message,
                                StringConnection playerConn)
Report the resources gained/lost by a player, and optionally (for trading) lost/gained by a second player. Sends PLAYERELEMENT messages, either to entire game, or to player only. Builds the resource-amount string used to report the trade as text. Takes and releases the gameList monitor for this game.

Used to report the resources gained from a roll, discard, or discovery (year-of-plenty) pick. Also used to report the "give" or "get" half of a resource trade.

Parameters:
gaName - Game name
rset - Resource set (from a roll, or the "give" or "get" side of a trade). Resource type SOCResourceConstants.UNKNOWN is ignored. Only positive resource amounts are sent (negative is ignored).
isLoss - If true, "give" (SOCPlayerElement.LOSE), otherwise "get" (SOCPlayerElement.GAIN)
mainPlayer - Player number "giving" if isLose==true, otherwise "getting". For each nonzero resource involved, PLAYERELEMENT messages will be sent about this player.
tradingPlayer - Player number on other side of trade, or -1 if no second player is involved. If not -1, PLAYERELEMENT messages will also be sent about this player.
message - Append resource numbers/types to this stringbuffer, format like "3 clay,3 wood"; can be null.
playerConn - Null or mainPlayer's connection; send messages here instead of sending to all players in game. Because trades are public, there is no such parameter for tradingPlayer.
See Also:
reportTrade(SOCGame, int, int), reportBankTrade(SOCGame, SOCResourceSet, SOCResourceSet), handleDISCARD(StringConnection, SOCDiscard), handleDISCOVERYPICK(StringConnection, SOCDiscoveryPick), handleROLLDICE(StringConnection, SOCRollDice)

checkTurn

protected boolean checkTurn(StringConnection c,
                            SOCGame ga)
make sure it's the player's turn

Parameters:
c - the connection for player
ga - the game
Returns:
true if it is the player's turn; false if another player's turn, or if this player isn't in the game

startGame

protected void startGame(SOCGame ga)
do the stuff you need to do to start a game

Parameters:
ga - the game

resetBoardAndNotify

private void resetBoardAndNotify(java.lang.String gaName,
                                 int requestingPlayer)
Reset the board, to a copy with same players but new layout.
  1. Reset the board, remember player positions.
  2. Send ResetBoardAuth to each client (like sending JoinGameAuth at new game) Humans will reset their copy of the game. Robots will leave the game and request to re-join. (This simplifies the robot client.)
  3. Send messages as if each human player has clicked "join" (except JoinGameAuth)
  4. Send as if each human player has clicked "sit here"
  5. If no robots, send to game as if someone else has clicked "start game", and set up state to begin game play.
  6. If there are robots, If there are robots, set up wait-request queue (robotJoinRequests). Game will wait for robots to send JOINGAME and SITDOWN, as they do when joining a newly created game. Once all robots have re-joined, the game will begin.
MUST be called ONLY from the one thread handling all inbound messages, or (race condition) the robots may ask to join before we've set up robotJoinRequests.


sendTurn

private void sendTurn(SOCGame ga,
                      boolean sendRollPrompt)
send whose turn it is. Optionally also send a prompt to roll. If the client is too old (1.0.6), it will ignore the prompt.

Parameters:
ga - the game
sendRollPrompt - whether to send a RollDicePrompt message afterwards

getBoardLayoutMessage

private SOCBoardLayout getBoardLayoutMessage(SOCGame ga)
put together the SOCBoardLayout message

Parameters:
ga - the game
Returns:
a board layout message

createNewGameEventRecord

private void createNewGameEventRecord()
create a new game event record


saveCurrentGameEventRecord

private void saveCurrentGameEventRecord(java.lang.String gn)
save the current game event record in the game record

Parameters:
gn - the name of the game

storeGameScores

protected void storeGameScores(SOCGame ga)
if all the players stayed for the whole game, record the scores in the database

Parameters:
ga - the game

recordGameEvent

protected void recordGameEvent(java.lang.String gameName,
                               java.lang.String event)
record events that happen during the game

Parameters:
gameName - the name of the game
event - the event

giveResources

protected void giveResources(java.lang.String mes,
                             SOCGame game)
this is a debugging command that gives resources to a player


broadcastGameStats

protected void broadcastGameStats(SOCGame ga)
this broadcasts game information to all people connected used to display the scores on the player client


checkForExpiredGames

public void checkForExpiredGames()
check for games that have expired and destroy them. If games are about to expire, send a warning.

See Also:
GAME_EXPIRE_WARN_MINUTES, SOCGameTimeoutChecker.run()

giveDevCard

protected void giveDevCard(java.lang.String mes,
                           SOCGame game)
this is a debugging command that gives a dev card to a player


main

public static void main(java.lang.String[] args)
Starting the server from the command line

Parameters:
args - arguments: port number