pictionary.pictionaryserver
Class PictionaryServer

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by java.awt.Window
              extended by java.awt.Frame
                  extended by javax.swing.JFrame
                      extended by pictionary.pictionaryserver.PictionaryServer
All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants

public final class PictionaryServer
extends javax.swing.JFrame

Responsible for sending messages between the connected clients, and between the Pictionary game and the clients. Keeps track of the clients with a HashMap where String is the clients unique name; there is one PictionaryServer.ClientConnection per connected client.

Author:
Kristoffer Nordkvist
See Also:
Serialized Form

Nested Class Summary
private  class PictionaryServer.ClientConnection
          Handles communication with one client; there is one ClientConnection per connected client.
private  class PictionaryServer.ClientConnectionMessage
          A simple class containing a PictionaryServer.ClientConnection and a String message.
private  class PictionaryServer.CloseWindowListener
          Overrides the default behavior when the window is closed.
private  class PictionaryServer.ConnectButtonListener
          The listener for disconnectOrConnectBtn.
private  class PictionaryServer.ServerThread
          Listen for new clients, if a new client is found it is passed to ClientConnection#ClientConnection(BlockingQueue, Socket) along with incomingMessages.
 
Nested classes/interfaces inherited from class javax.swing.JFrame
javax.swing.JFrame.AccessibleJFrame
 
Nested classes/interfaces inherited from class java.awt.Frame
java.awt.Frame.AccessibleAWTFrame
 
Nested classes/interfaces inherited from class java.awt.Window
java.awt.Window.AccessibleAWTWindow
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
 java.lang.String category
          The current word category in the Pictionary game.
private  java.util.HashMap<java.lang.String,PictionaryServer.ClientConnection> clientConnections
          The collection that stores all the client connections.
private  javax.swing.JButton disconnectOrConnectBtn
          The button used when starting or shutting down the server.
private  java.lang.String host
          This server's hostname.
private  java.util.HashSet<java.lang.String> illegalUsernames
          A collection of usernames that are unavailable.
private  java.util.concurrent.LinkedBlockingQueue<PictionaryServer.ClientConnectionMessage> incomingMessages
          The server's queue with incoming messages.
private  PictionaryGame pictionaryGame
          The PictionaryGame instance used by the server.
private  int port
          The port on which this server is listening.
private  boolean running
          True if the server is running, else false.
private  java.net.ServerSocket serverSocket
          Responsible for accepting new connections.
private  PictionaryServer.ServerThread serverThread
          The PictionaryServer.ServerThread instance used for accepting and creating new client connections.
private  boolean shutdown
          True if the server thread is shut down, else false.
private  boolean wasShutDown
          True if this server has been shut down, else false.
 java.util.ArrayList<java.lang.String> words
          The words used in the Pictionary game.
 
Fields inherited from class javax.swing.JFrame
accessibleContext, EXIT_ON_CLOSE, rootPane, rootPaneCheckingEnabled
 
Fields inherited from class java.awt.Frame
CROSSHAIR_CURSOR, DEFAULT_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, ICONIFIED, MAXIMIZED_BOTH, MAXIMIZED_HORIZ, MAXIMIZED_VERT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NORMAL, NW_RESIZE_CURSOR, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, W_RESIZE_CURSOR, WAIT_CURSOR
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface javax.swing.WindowConstants
DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
PictionaryServer(java.lang.String host, int port, java.lang.String category, java.util.ArrayList<java.lang.String> words)
          The server's constructor.
 
Method Summary
private  void acceptConnection(PictionaryServer.ClientConnection newConnection)
          Adds a connection to clientConnections, adds the client's name to illegalUsernames and informs all connected clients that someone connected to the server.
private  void clientDisconnected(PictionaryServer.ClientConnection client)
          Removes a client from clientConnections, removes the username for illegalUsernames and informs all connected clients that someone left the server.
private  void connect()
          Creates a new ServerSocket and starts listening for new connections.
private  void connectionToClientClosedWithError(PictionaryServer.ClientConnection client, java.lang.String errorMessage)
          Calls clientDisconnected(ClientConnection) and prints a message to standard error output.
private  java.util.List<java.lang.String> getClients()
          Gets the connected client's unique names.
private  void initIllegalNames()
          Clears the list of illegal names and adds some standard ones.
static void main(java.lang.String[] args)
          Tries to read settings.txt and then start the server.
private  void messageReceived(PictionaryServer.ClientConnection client, Message message)
          Called when a new message has been received
private  void restartServer(int port)
          Starts the server again by creating a new ServerSocket and listener thread.
private  void sendToAll(Message message)
          Sends a message to all clients.
private  boolean sendToOne(java.lang.String recipient, Message message)
          Sends a message to one client.
private  void shutDownServer()
          Disconnects all clients and stops accepting new connections.
private  void shutdownServerSocket()
          Clears the queue of incoming messages, shuts down the listener thread, sets the listener thread and ServerSocket to null.
 boolean validusername(java.lang.String username)
          Checks whether and username is valid or not.
 
Methods inherited from class javax.swing.JFrame
addImpl, createRootPane, frameInit, getAccessibleContext, getContentPane, getDefaultCloseOperation, getGlassPane, getGraphics, getJMenuBar, getLayeredPane, getRootPane, getTransferHandler, isDefaultLookAndFeelDecorated, isRootPaneCheckingEnabled, paramString, processWindowEvent, remove, repaint, setContentPane, setDefaultCloseOperation, setDefaultLookAndFeelDecorated, setGlassPane, setIconImage, setJMenuBar, setLayeredPane, setLayout, setRootPane, setRootPaneCheckingEnabled, setTransferHandler, update
 
Methods inherited from class java.awt.Frame
addNotify, getCursorType, getExtendedState, getFrames, getIconImage, getMaximizedBounds, getMenuBar, getState, getTitle, isResizable, isUndecorated, remove, removeNotify, setCursor, setExtendedState, setMaximizedBounds, setMenuBar, setResizable, setState, setTitle, setUndecorated
 
Methods inherited from class java.awt.Window
addPropertyChangeListener, addPropertyChangeListener, addWindowFocusListener, addWindowListener, addWindowStateListener, applyResourceBundle, applyResourceBundle, createBufferStrategy, createBufferStrategy, dispose, getBufferStrategy, getFocusableWindowState, getFocusCycleRootAncestor, getFocusOwner, getFocusTraversalKeys, getGraphicsConfiguration, getIconImages, getInputContext, getListeners, getLocale, getModalExclusionType, getMostRecentFocusOwner, getOwnedWindows, getOwner, getOwnerlessWindows, getToolkit, getWarningString, getWindowFocusListeners, getWindowListeners, getWindows, getWindowStateListeners, hide, isActive, isAlwaysOnTop, isAlwaysOnTopSupported, isFocusableWindow, isFocusCycleRoot, isFocused, isLocationByPlatform, isShowing, pack, paint, postEvent, processEvent, processWindowFocusEvent, processWindowStateEvent, removeWindowFocusListener, removeWindowListener, removeWindowStateListener, reshape, setAlwaysOnTop, setBounds, setBounds, setCursor, setFocusableWindowState, setFocusCycleRoot, setIconImages, setLocationByPlatform, setLocationRelativeTo, setMinimumSize, setModalExclusionType, setSize, setSize, setVisible, show, toBack, toFront
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalPolicy, getInsets, getLayout, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, print, printComponents, processContainerEvent, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resize, resize, setBackground, setComponentOrientation, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setName, setPreferredSize, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface java.awt.MenuContainer
getFont, postEvent
 

Field Detail

clientConnections

private java.util.HashMap<java.lang.String,PictionaryServer.ClientConnection> clientConnections
The collection that stores all the client connections. Clients are identified with their unique name.


pictionaryGame

private PictionaryGame pictionaryGame
The PictionaryGame instance used by the server.


incomingMessages

private java.util.concurrent.LinkedBlockingQueue<PictionaryServer.ClientConnectionMessage> incomingMessages
The server's queue with incoming messages. Every time a PictionaryServer.ClientConnection receives a message, it puts that message in this queue.


serverSocket

private java.net.ServerSocket serverSocket
Responsible for accepting new connections.


serverThread

private PictionaryServer.ServerThread serverThread
The PictionaryServer.ServerThread instance used for accepting and creating new client connections.


shutdown

private volatile boolean shutdown
True if the server thread is shut down, else false. Used in PictionaryServer.ServerThread.


port

private final int port
The port on which this server is listening.


host

private final java.lang.String host
This server's hostname.


disconnectOrConnectBtn

private javax.swing.JButton disconnectOrConnectBtn
The button used when starting or shutting down the server.


running

private boolean running
True if the server is running, else false. Used by the server's GUI.


wasShutDown

private boolean wasShutDown
True if this server has been shut down, else false. Used by the server's GUI.


illegalUsernames

private java.util.HashSet<java.lang.String> illegalUsernames
A collection of usernames that are unavailable.


category

public final java.lang.String category
The current word category in the Pictionary game.


words

public final java.util.ArrayList<java.lang.String> words
The words used in the Pictionary game.

Constructor Detail

PictionaryServer

public PictionaryServer(java.lang.String host,
                        int port,
                        java.lang.String category,
                        java.util.ArrayList<java.lang.String> words)
The server's constructor.

Parameters:
host - The server's hostname.
port - The port that the server listens for new connections on.
category - The Pictionary game's word category.
words - The list of words to be used in the Pictionary game.
Method Detail

initIllegalNames

private void initIllegalNames()
Clears the list of illegal names and adds some standard ones.


validusername

public boolean validusername(java.lang.String username)
Checks whether and username is valid or not.

Parameters:
username - The name to check for validity.
Returns:
True if the username is legal, else false.

connect

private void connect()
              throws java.io.IOException
Creates a new ServerSocket and starts listening for new connections.

Throws:
java.io.IOException - If the ServerSocket cannot be created.

messageReceived

private void messageReceived(PictionaryServer.ClientConnection client,
                             Message message)
Called when a new message has been received

Parameters:
client - The client that sent the message.
message - The message that was sent from the client.

getClients

private java.util.List<java.lang.String> getClients()
Gets the connected client's unique names.

Returns:
A list containing the unique identifiers for each client.

shutdownServerSocket

private void shutdownServerSocket()
Clears the queue of incoming messages, shuts down the listener thread, sets the listener thread and ServerSocket to null.


restartServer

private void restartServer(int port)
                    throws java.io.IOException
Starts the server again by creating a new ServerSocket and listener thread. Should be called after shutDownServer().

Parameters:
port - The port which the server will listen on for new connections.
Throws:
java.io.IOException - If a new ServerSocket could not be created.

shutDownServer

private void shutDownServer()
Disconnects all clients and stops accepting new connections.


sendToAll

private void sendToAll(Message message)
Sends a message to all clients.

Parameters:
message - The message to be sent.

sendToOne

private boolean sendToOne(java.lang.String recipient,
                          Message message)
Sends a message to one client.

Parameters:
recipient - The receiving client.
message - The message to be sent.
Returns:
True if the message was sent, else false.

acceptConnection

private void acceptConnection(PictionaryServer.ClientConnection newConnection)
Adds a connection to clientConnections, adds the client's name to illegalUsernames and informs all connected clients that someone connected to the server.

Parameters:
newConnection - The client that connected to the server.

clientDisconnected

private void clientDisconnected(PictionaryServer.ClientConnection client)
Removes a client from clientConnections, removes the username for illegalUsernames and informs all connected clients that someone left the server.

Parameters:
client - The client that has disconnected from the server.

connectionToClientClosedWithError

private void connectionToClientClosedWithError(PictionaryServer.ClientConnection client,
                                               java.lang.String errorMessage)
Calls clientDisconnected(ClientConnection) and prints a message to standard error output.

Parameters:
client - The client that disconnected.
errorMessage - The message to print.

main

public static void main(java.lang.String[] args)
Tries to read settings.txt and then start the server. If settings.txt does not exist, a new one is created and we read that one instead.