Logo AND Algorithmique Numérique Distribuée

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