wangzhengquan
2020-10-13 1577a5d11a9341e506331df86870997d49fd441b
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
#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 send_buf[MAXLINE];
    net_mod_recv_msg_t *recv_arr;
    int recv_arr_size, i;
    net_node_t node_arr[] = {
        {"localhost", port, 11},
        {"localhost", port, 12},
        {"localhost", port, 13},
        {"localhost", port, 14}
    };
 
  while (fgets(send_buf, MAXLINE, stdin) != NULL) {
      // 收到消息的节点即使没有对应的信息, 也要回复一个表示无的消息,否则会一直等待
    client.sendandrecv( node_arr, 4, send_buf, strlen(send_buf), &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);
  }
}
 
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);
}