-
Notifications
You must be signed in to change notification settings - Fork 0
HelloWorld Example
redParrot17 edited this page Dec 2, 2018
·
3 revisions
This example demonstrates how to create an instance of the TcpServer and TcpClient, connect them together, register a message listener, send a message to the server, and how to shut everything down.
The client will send a message to the server. Once the server receives the message, it will echo it back to the client. When the client receives the message from the server, it will print out what the message was. If everything works correctly, the client should print out the same message that it originally sent.
import client.ClientException;
import client.TcpClient;
import listener_references.ServerConnection;
import server.ServerException;
import server.TcpServer;
public class Example {
public static void main(String[] args) throws ServerException, ClientException {
// Create and start the TcpServer
TcpServer server = new TcpServer(7070, 0, 5, true);
// Create and connect the TcpClient
TcpClient client = new TcpClient("localhost", 7070, true);
// Add a message listener to the server
server.addMessageListener(message -> {
// Double check to make sure the connection is an instance of a ServerConnection
if (!message.getConnection().asServerConnection().isPresent()) {
return;
}
ServerConnection connection = message.getConnection().asServerConnection().get();
connection.replyText(message.getMessage());
});
// Add a message listener to the client
client.addMessageListener(message -> {
String text = message.getMessage();
System.out.println(text);
});
// Send a message to the server
client.sendText("HelloWorld!");
// Wait a little bit
try { Thread.sleep(5000);
} catch (InterruptedException ignore){}
// Disconnect and shutdown both the client and server
client.close();
server.close();
}
}