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

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