![]() |
MpsSimpleExample |
Let's say we need to have two programs interact with each other. They need to be able to access each others' functionality - that is, one of them is providing a service to the other. Let's say that this service (it's a simple example, OK?) is to write out a log entry to a file.
1.2 The Code
1.2.1 MPS IDL File
We might choose to define part of the interface like this (logging.mps):
namespace Logging {
interface LogServer {
// Log a string to our current file.
// Returns true for success, and false for failure.
bool logString(string toLog);
}
}
Performing the command
mpsidl -c -o logging logging.mps
produces the files logging.h and logging.cc, which contain definitions for C++ server stubs and client proxies implementing this interface.
One of our C++ programs needs to make use of this new functionality:
#include <mps.h> #include <mpsnaming.h> #include "logging.h"
using namespace org::hebe::mps::naming;
int main(int argc, char *argv[]) {
NamingServiceProxy ns("mps://localhost:9091/", NULL);
Logging::LogServerProxy logServer("Logserver", &ns);
...
if (logServer.logString("Startup successful") == false) {
// Couldn't write log message...
}
...
}
We choose to implement the server in Java. Running the command
mpsidl -j logging.mps
creates the directory Logging/ which contains Java source code implementing package Logging, which provides both client- and server-side interfaces to the interface defined in logging.mps.
We write our implementation of the server like this:
import org.hebe.mps.*; import org.hebe.mps.naming.*; import Logging.*;
public class LogServerImpl implements LogServer {
public static void main(String[] args) {
NamingService ns = new NamingServiceProxy("mps://localhost:9091/", null);
new LogServerServer("Logserver", ns, new LogServerImpl());
}
private LoggingImpl() {
}
public boolean logString(String toLog) {
// Implement server-side here...
}
}
The equivalent C++ code might look like:
#include <mps.h> #include <mpsnaming.h> #include "logging.h"
using namespace org::hebe::mps::naming; using namespace Logging;
class LogServerImpl: public LogServer {
virtual bool logString(string const &toLog) {
// Implement server-side here...
}
};
int main() {
NamingServiceProxy ns("mps://localhost:9091/", NULL);
LogServerImpl impl;
LogServerServer server("Logserver", &ns, impl);
server.mainloop(); }