Class TcpServer

java.lang.Object
it.polimi.ingsw.communication.tcp_server.TcpServer
All Implemented Interfaces:
Runnable
Direct Known Subclasses:
SugarServer

public abstract class TcpServer extends Object implements Runnable
  • Field Details

    • port

      private final int port
    • socket

      private final ServerSocket socket
    • clients

      private final Set<Socket> clients
    • logStream

      private PrintStream logStream
    • logHeader

      private String logHeader
  • Constructor Details

  • Method Details

    • beforeStart

      protected void beforeStart()
      The server calls this function before starting his blocking accept-connection loop
    • onConnect

      protected void onConnect(Socket client)
      The server calls this function any time a new client connects. Subclasses that override this function MUST call super().
      Parameters:
      client - the socket communicating with the client
    • onDisconnect

      protected void onDisconnect(Socket client)
      The server calls this function any time a client disconnects Subclasses that override this function MUST call super().
      Parameters:
      client - the socket communicating with the client
    • onMessage

      protected void onMessage(Socket client, String message)
      The server calls this function any time it receives a message from the client. Subclasses that override this function MUST call super().
      Parameters:
      client - the socket communicating with the client
      message - the message received from the client
    • setLogStream

      public void setLogStream(PrintStream logStream)
    • setLogHeader

      public void setLogHeader(String logHeader)
    • log

      protected void log(String message)
      Logs the message to the current logStream
      Parameters:
      message - any log message
    • run

      public final void run()
      Specified by:
      run in interface Runnable
    • inputHandler

      private void inputHandler(Socket client, ExecutorService executorService)
      Handles incoming messages
      Parameters:
      client - the client socket
      executorService - an ExecutorService
    • readLine

      private String readLine(BufferedReader in) throws IOException
      Throws:
      IOException
    • send

      public void send(String message, Socket client) throws IOException
      Removes all whitespaces from the message, adds a newline at the end and sends it to the client
      Parameters:
      message - any message string
      client - any client socket
      Throws:
      IOException - if an I/O error occurs when creating the output stream or if the socket is not connected
    • disconnectClient

      protected void disconnectClient(Socket client) throws IOException
      Disconnects the server from the client
      Parameters:
      client - any client socket
      Throws:
      IOException - if an I/O error occurs when closing the socket