|
VRPN 06.04 |
A complete vrpn_Connection example This example creates a VRPN server that emits test messages to anyone that connects to it. It also registers a callback handler to handle any test messages that are sent. This callback is called both for the locally-sent messages and for any that are sent by a remote connection linked to its local one. The messages are sent once per second. #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <vrpn_Connection.h>
// This is the callback handler that will print the string from any
// incoming message (and also the locally-packed ones).
int my_handler(void *userdata, vrpn_HANDLERPARAM p) {
char *prompt = (char*)userdata; // Type-cast to the right type
printf("%s:%s\n", prompt, p.buffer); // Assume it's a string message
return 0;
}
main() {
// Open a connection and register my sender name and the type of
// message that I care about.
vrpn_Synchronized_Connection *connection = new vrpn_Synchronized_Connection();
long my_type = connection->register_message_type("Test_type");
long my_id = connection->register_sender("Test0");
// Register the callback handler
connection->register_handler(my_type, my_handler,
(void*)"Test message", my_id);
// Once a second, pack a message and then call mainloop() to cause it
// to be sent and also to call the callback for any messages.
while (1) {
struct timeval now;
gettimeofday(&now,NULL);
connection->pack_message(sizeof("Hi!"), now, my_type, my_id,
"Hi!", vrpn_CONNECTION_RELIABLE);
connection->mainloop();
sleep(1);
}
}
Note that a remote version of the above example would look exactly the same, except that it would pass the name of the server to the vrpn_Connection constructor. Also note that devices form an abstraction layer above the vrpn_Connection class, hiding the details of packing and unpacking the messages from application and server code. It is possible for user-level code to access a connection directly, as described above; VRPN could be used as a message-passing system for application objects. |