1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
| #include "net_mod_server_socket.h"
| #include "net_mod_socket.h"
| #include "shm_mm.h"
| #include "dgram_mod_socket.h"
| #include "usg_common.h"
|
| void server(int port) {
| NetModServerSocket *serverSocket = new NetModServerSocket(port);
| serverSocket->start();
| }
|
| void client(int port ){
| NetModSocket client;
| char content[MAXLINE];
| char action[512];
| char topic[512];
| net_mod_recv_msg_t *recv_arr;
| int recv_arr_size, i, n;
| int node_arr_size = 3;
| //192.168.20.104
| net_node_t node_arr[] = {
| {"192.168.5.22", port, 11},
| {"192.168.20.10", port, 12},
| {"localhost", port, 13}
| };
|
| int pub_node_arr_size = 3;
| net_node_t pub_node_arr[] = {
| {"192.168.5.22", port, 8},
| {"192.168.20.10", port, 8},
| {"localhost", port, 8}
| };
|
| while (true) {
| //printf("Usage: pub <topic> [content] or sub <topic>\n");
| printf("Can I help you? pub, send or quit\n");
| scanf("%s",action);
|
| if(strcmp(action, "pub") == 0) {
| printf("Please input topic and content\n");
| scanf("%s %s", topic, content);
|
| n = client.pub(pub_node_arr, pub_node_arr_size, topic, strlen(topic)+1, content, strlen(content)+1);
| printf("pub %d\n", n);
| }
| else if(strcmp(action, "send") == 0) {
| getc(stdin);
| printf("Please input content\n");
|
| if (fgets(content, MAXLINE, stdin) != NULL) {
| // 收到消息的节点即使没有对应的信息, 也要回复一个表示无的消息,否则会一直等待
| n = client.sendandrecv( node_arr, node_arr_size, content, strlen(content), &recv_arr, &recv_arr_size);
| for(i=0; i<recv_arr_size; i++) {
| printf("host:%s, port: %d, key:%d, content: %s\n",
| recv_arr[i].host,
| recv_arr[i].port,
| recv_arr[i].key,
| recv_arr[i].content
| );
| }
| //使用完后,不要忘记释放掉
| NetModSocket::free_recv_msg_arr(recv_arr, recv_arr_size);
| }
| }
| else if(strcmp(action, "quit") == 0) {
| break;
| } else {
| printf("error input argument\n");
| continue;
| }
|
| }
|
|
|
| }
|
| int main(int argc, char *argv[]) {
| shm_init(512);
|
| int port;
| if (argc < 3) {
| fprintf(stderr, "Usage: %s %s|%s <PORT> \n", argv[0], "server", "client");
| return 1;
| }
|
| port = atoi(argv[2]);
|
|
| if (strcmp("server", argv[1]) == 0 ) {
| server(port);
| }
|
| if (strcmp("client", argv[1]) == 0)
| client(port);
| }
|
|