Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
regenerate output files with lastest version of the stuff
[simgrid.git] / doc / gtut-files / 05-globals.c
1 #include <stdio.h>
2 #include <gras.h>
3
4 typedef struct {
5    int killed;
6 } server_data_t;
7    
8
9 int server_kill_cb(gras_msg_cb_ctx_t ctx, void *payload) {
10   gras_socket_t client = gras_msg_cb_ctx_from(ctx);
11   server_data_t *globals=(server_data_t*)gras_userdata_get();
12    
13   fprintf(stderr,"Argh, killed by %s:%d! Bye folks...\n",
14           gras_socket_peer_name(client), gras_socket_peer_port(client));
15   
16   globals->killed = 1;
17    
18   return 0;
19 } /* end_of_kill_callback */
20
21 int server_hello_cb(gras_msg_cb_ctx_t ctx, void *payload) {
22   gras_socket_t client = gras_msg_cb_ctx_from(ctx);
23
24   fprintf(stderr,"Cool, we received the message from %s:%d.\n",
25           gras_socket_peer_name(client), gras_socket_peer_port(client));
26   
27   return 0;
28 } /* end_of_hello_callback */
29
30 int server(int argc, char *argv[]) {
31   gras_socket_t mysock;   /* socket on which I listen */
32   server_data_t *globals;
33   
34   gras_init(&argc,argv);
35
36   globals=gras_userdata_new(server_data_t*);
37   globals->killed=0;
38
39   gras_msgtype_declare("hello", NULL);
40   gras_msgtype_declare("kill", NULL);
41   mysock = gras_socket_server(atoi(argv[1]));
42    
43   gras_cb_register("hello",&server_hello_cb);   
44   gras_cb_register("kill",&server_kill_cb);
45
46   while (!globals->killed) {
47      gras_msg_handle(-1); /* blocking */
48   }
49     
50   gras_exit();
51   return 0;
52 }
53
54 int client(int argc, char *argv[]) {
55   gras_socket_t mysock;   /* socket on which I listen */
56   gras_socket_t toserver; /* socket used to write to the server */
57
58   gras_init(&argc,argv);
59
60   gras_msgtype_declare("hello", NULL);
61   gras_msgtype_declare("kill", NULL);
62   mysock = gras_socket_server_range(1024, 10000, 0, 0);
63   
64   fprintf(stderr,"Client ready; listening on %d\n", gras_socket_my_port(mysock));
65   
66   gras_os_sleep(1.5); /* sleep 1 second and half */
67   toserver = gras_socket_client(argv[1], atoi(argv[2]));
68   
69   gras_msg_send(toserver,"hello", NULL);
70   fprintf(stderr,"we sent the data to the server on %s. Let's do it again for fun\n", gras_socket_peer_name(toserver));
71   gras_msg_send(toserver,"hello", NULL);
72    
73   fprintf(stderr,"Ok. Enough. Have a rest, and then kill the server\n");
74   gras_os_sleep(5); /* sleep 1 second and half */
75   gras_msg_send(toserver,"kill", NULL);
76
77   gras_exit();
78   return 0;
79 }