Class TcpServer
java.lang.Object
it.polimi.ingsw.communication.tcp_server.TcpServer
- All Implemented Interfaces:
Runnable
- Direct Known Subclasses:
SugarServer
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate Stringprivate PrintStreamprivate final intprivate final ServerSocket -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidThe server calls this function before starting his blocking accept-connection loopprotected voiddisconnectClient(Socket client) Disconnects the server from the clientprivate voidinputHandler(Socket client, ExecutorService executorService) Handles incoming messagesprotected voidLogs the message to the current logStreamprotected voidThe server calls this function any time a new client connects.protected voidonDisconnect(Socket client) The server calls this function any time a client disconnects Subclasses that override this function MUST call super().protected voidThe server calls this function any time it receives a message from the client.private Stringfinal voidrun()voidRemoves all whitespaces from the message, adds a newline at the end and sends it to the clientvoidsetLogHeader(String logHeader) voidsetLogStream(PrintStream logStream)
-
Field Details
-
port
private final int port -
socket
-
clients
-
logStream
-
logHeader
-
-
Constructor Details
-
TcpServer
- Throws:
IOException
-
-
Method Details
-
beforeStart
protected void beforeStart()The server calls this function before starting his blocking accept-connection loop -
onConnect
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
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
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 clientmessage- the message received from the client
-
setLogStream
-
setLogHeader
-
log
Logs the message to the current logStream- Parameters:
message- any log message
-
run
public final void run() -
inputHandler
Handles incoming messages- Parameters:
client- the client socketexecutorService- an ExecutorService
-
readLine
- Throws:
IOException
-
send
Removes all whitespaces from the message, adds a newline at the end and sends it to the client- Parameters:
message- any message stringclient- any client socket- Throws:
IOException- if an I/O error occurs when creating the output stream or if the socket is not connected
-
disconnectClient
Disconnects the server from the client- Parameters:
client- any client socket- Throws:
IOException- if an I/O error occurs when closing the socket
-