Skip to content

Creating a TCP Server using the BialettiTCPServer

Alessandro Salerno edited this page Aug 24, 2022 · 1 revision

A BialettiTCPServer is nothing more than a BialettiRunnableService with TCP Server functionality built in. Init, shutdown, handle and exception handler methods work exactly the same way they do in other services.

The architecture

A BialettiTCPServer listens for new connections on a given port. When a client connects, it creates a representation of it by calling the getNewClient method (Which is abstract, thus user-defined). The getNewClientMethod should return a new instance of a class that extends BialettiTCPServerClient, this class should also be passed as a generic parameter to the server, as shown here:

public class ConnectedClient extends BialettiTCPServerClient<MyTCPServer> {
    private String username;
    
    public ConnectedClient(BialettiTCPConnection c, Server s) {
        super(c, s);
    }

    @Override
    @BialettiInitMethod
    public void onConnect() throws Exception {
        System.out.println("New Client Connected: " + getConnection().getSocket().toString());

        username = getConnection().receive();
        System.out.println("[+] User " + username + " logged in");
        getServer().broadcast(username + " joined");
    }

    @Override
    @BialettiEndMethod
    public void onClose() throws Exception {
        System.out.println(username + " left");
    }
}

public class MyTCPServer extends BialettiTCPServer<ConnectedClient> {
    public MyTCPServer(int port) {
        super(port);
    }

    @Override
    protected ConnectedClient getNewClient(BialettiTCPConnection bialettiConnection) {
        return new ConnectedClient(bialettiConnection, this);
    }

    @Override
    @BialettiInitMethod
    public void onStart() throws Exception { // throws clause is included to take advantage of exception handling
        System.out.println("[+] Server started");
    }

    @Override
    @BialettiEndMethod
    public void onStop() throws Exception { // throws clause is included to take advantage of exception handling
        System.out.println("[-] Server stopped");
    }
}
Clone this wiki locally