| # 26. Messaging In client/server mode the TCP connection between the client and the server can also be used to send messages from the client to the server. Possible usecases could be: - shutting down and restarting the server - triggering server backup - using a customized login strategy to restrict the number of allowed client connections Here is some example code how this can be done. First we need to decide on a class that we want to use as the message. Any object that is storable in db4o can be used as a message, but strings and other simple types will not be carried (as they are not storable in db4o on their own). Let's create a dedicated class:
`class MyClientServerMessage { private String info; public MyClientServerMessage(String info){ this.info = info; } public Strint toString(){ return "MyClientServerMessage: " + info; } }`
Now we have to add some code to the server to react to arriving messages. This can be done by configuring a MessageRecipient object on the server. Let's simply print out all objects that arrive as messages. For the following we assume that we already have an ObjectServer object, opened with Db4o.openServer() .
`objectServer.ext().configure().setMessageRecipient( new MessageRecipient() { public void processMessage( ObjectContainer objectContainer, Object message) { // message objects will arrive in this code block System.out.println(message); } });`
Here is what we would do on the client to send the message:
`MessageSender sender = clientObjectContainer.ext().configure().getMessageSender(); sender.send(new MyClientServerMessage("Hello from client.");`
The MessageSender object on the client can be reused to send multiple messages. -- generated by Doctor courtesy of db4objects Inc.