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:

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:

MyClientServerMessage.java
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02 03package com.db4odoc.messaging; 04 05 06class MyClientServerMessage { 07 08 private String info; 09 10 public MyClientServerMessage(String info){ 11 this.info = info; 12 } 13 14 public String toString(){ 15 return "MyClientServerMessage: " + info; 16 } 17 18}

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().

MessagingExample.java
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02 03package com.db4odoc.messaging; 04 05import com.db4o.Db4o; 06import com.db4o.ObjectContainer; 07import com.db4o.ObjectServer; 08import com.db4o.config.Configuration; 09import com.db4o.messaging.MessageRecipient; 10import com.db4o.messaging.MessageSender; 11 12 13public class MessagingExample { 14 private final static String DB4O_FILE_NAME="reference.db4o"; 15 16 public static void configureServer() { 17 Configuration configuration = Db4o.newConfiguration(); 18 configuration.clientServer().setMessageRecipient(new MessageRecipient() { 19 public void processMessage(ObjectContainer objectContainer, 20 Object message) { 21 // message objects will arrive in this code block 22 System.out.println(message); 23 } 24 }); 25 ObjectServer objectServer = Db4o.openServer(configuration, DB4O_FILE_NAME, 0); 26 27 try { 28 ObjectContainer clientObjectContainer = objectServer.openClient(); 29 // Here is what we would do on the client to send the message 30 MessageSender sender = clientObjectContainer.ext().configure().clientServer().getMessageSender(); 31 32 sender.send(new MyClientServerMessage("Hello from client.")); 33 clientObjectContainer.close(); 34 } finally { 35 objectServer.close(); 36 } 37 } 38 // end configureServer 39 40}

The MessageSender object on the client can be reused to send multiple messages.