You are here: Client-Server > Messaging

Messaging

In client/server it possible to send messages between a client and the server. Possible use cases could be:

Sending and Receiving Messages

First you need to decide on a class that you want to use as the message. Any object that is storable in db4o can be used as a message. Of course you use multiple classes for representing different messages. Let's create a dedicated class.

public  class HelloMessage {
    private  final String message;

    public HelloMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return message;
    }
}
HelloMessage.java: The message class

Now you need to register a handler to handle arriving messages. This can be done by configuring a message recipient on the server. Let's simply print out the arriving message. Additionally we answer to the client with another message.

ServerConfiguration configuration = Db4oClientServer.newServerConfiguration();
configuration.networking().messageRecipient(new MessageRecipient() {
    public  void processMessage(MessageContext messageContext, Object o) {
        System.out.println("The server received a '" + o + "' message");
        // you can respond to the client
        messageContext.sender().send(new HelloMessage("Hi Client!"));
    }
});
ObjectServer server = Db4oClientServer.openServer(configuration, DATABASE_FILE, PORT_NUMBER);
MessagingExample.java: configure a message receiver for the server

The same can be done on the client. Register a handler for the received messages.

ClientConfiguration configuration = Db4oClientServer.newClientConfiguration();
configuration.networking().messageRecipient(new MessageRecipient() {
    public  void processMessage(MessageContext messageContext, Object o) {
        System.out.println("The client received a '" + o + "' message");
    }
});
MessagingExample.java: configure a message receiver for a client

Now on the client we can get a message sender. The message sender allows you to send a message to the server. In this example we send a hello message.

MessageSender sender = configuration.messageSender();
ObjectContainer container = Db4oClientServer.openClient(configuration, "localhost", PORT_NUMBER, USER_AND_PASSWORD, USER_AND_PASSWORD);


sender.send(new HelloMessage("Hi Server!"));
MessagingExample.java: Get the message sender and use it