1 /* ping - ping/pong demo of GRAS features */
3 /* Copyright (c) 2003, 2004, 2005 Martin Quinson. All rights reserved. */
5 /* This program is free software; you can redistribute it and/or modify it
6 * under the terms of the license (GNU LGPL) which comes with this package. */
10 XBT_LOG_EXTERNAL_DEFAULT_CATEGORY(Ping);
12 /* Global private data */
19 static int server_cb_ping_handler(gras_msg_cb_ctx_t ctx, void *payload)
23 /* 1. Get the payload into the msg variable, and retrieve my caller */
24 int msg = *(int *) payload;
25 gras_socket_t expeditor = gras_msg_cb_ctx_from(ctx);
27 /* 2. Retrieve the server's state (globals) */
29 server_data_t *globals = (server_data_t *) gras_userdata_get();
30 globals->endcondition = 0;
32 /* 3. Log which client connected */
33 INFO3(">>>>>>>> Got message PING(%d) from %s:%d <<<<<<<<",
35 gras_socket_peer_name(expeditor), gras_socket_peer_port(expeditor));
37 /* 4. Change the value of the msg variable */
39 /* 5. Send it back as payload of a pong message to the expeditor */
41 gras_msg_send(expeditor, "pong", &msg);
43 /* 6. Deal with errors: add some details to the exception */
45 gras_socket_close(globals->sock);
46 RETHROW0("Unable answer with PONG: %s");
49 INFO0(">>>>>>>> Answered with PONG(4321) <<<<<<<<");
51 /* 7. Set the endcondition boolean to true (and make sure the server stops after receiving it). */
52 globals->endcondition = 1;
54 /* 8. Tell GRAS that we consummed this message */
56 } /* end_of_server_cb_ping_handler */
58 int server(int argc, char *argv[])
60 server_data_t *globals;
64 /* 1. Init the GRAS infrastructure and declare my globals */
65 gras_init(&argc, argv);
66 globals = gras_userdata_new(server_data_t);
68 /* 2. Get the port I should listen on from the command line, if specified */
73 INFO1("Launch server (port=%d)", port);
75 /* 3. Create my master socket */
76 globals->sock = gras_socket_server(port);
78 /* 4. Register the known messages. This function is called twice here, but it's because
79 this file also acts as regression test, no need to do so yourself of course. */
80 ping_register_messages();
81 ping_register_messages(); /* just to make sure it works ;) */
83 /* 5. Register my callback */
84 gras_cb_register("ping", &server_cb_ping_handler);
86 INFO1(">>>>>>>> Listening on port %d <<<<<<<<",
87 gras_socket_my_port(globals->sock));
88 globals->endcondition = 0;
90 /* 6. Wait up to 10 minutes for an incomming message to handle */
91 gras_msg_handle(10.0);
94 if (!globals->endcondition)
95 WARN0("An error occured, the endcondition was not set by the callback");
97 /* 8. Free the allocated resources, and shut GRAS down */
98 gras_socket_close(globals->sock);
104 } /* end_of_server */