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