wangzhengquan
2021-01-22 7e1e05df84d57d2d7c3a622d0ece0d4fe7b1fc8c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include "bus_server_socket.h"
#include "shm_mod_socket.h"
#include "shm_mm_wrapper.h"
#include "usg_common.h"
#include "mm.h"
 
BusServerSocket * server_socket;
void sigint_handler(int sig) {
  
   exit(0);
}
 
void server(int key) {
  server_socket = new BusServerSocket();
 
  server_socket->bind( key);
   
  server_socket->start();
}
 
 
void *run_recv(void *skptr) {
  pthread_detach(pthread_self());
  void *recvbuf;
  int size;
  int key;
  ShmModSocket *sk = (ShmModSocket *)skptr;
  while ( true) {
    sk->recvfrom( &recvbuf, &size, &key);
    printf("收到订阅消息:%s\n", recvbuf);
    free(recvbuf);
  }
  
}
 
void client(int key) {
  ShmModSocket *sk = new ShmModSocket();
  
  pthread_t tid;
  pthread_create(&tid, NULL, run_recv, (void *)sk);
  int size;
  
  char action[512];
  char topic[512];
  char content[512];
  long i = 0;
  while (true) {
    //printf("Usage: pub <topic> [content] or sub <topic>\n");
    printf("Can I help you? sub, pub, desub or quit\n");
    scanf("%s",action);
    
    if(strcmp(action, "sub") == 0) {
      printf("Please input topic!\n");
      scanf("%s", topic);
      if (sk->sub(topic, strlen(topic),  key) == 0) {
         printf("%d Sub success!\n", sk->get_key());
      } else {
        printf("Sub failture!\n");
        exit(0);
      }
     
    } else if(strcmp(action, "desub") == 0) {
      printf("Please input topic!\n");
      scanf("%s", topic);
      if (sk->desub(topic, strlen(topic),  key) == 0) {
         printf("%d Desub success!\n", sk->get_key());
      } else {
        printf("Desub failture!\n");
        exit(0);
      }
     
    } else if(strcmp(action, "pub") == 0) {
      // printf("%s %s %s\n", action, topic, content);
      printf("Please input topic and content\n");
      scanf("%s %s", topic, content);
      if(sk->pub(topic, strlen(topic)+1, content, strlen(content)+1,  key) == 0){
        printf("%d Pub success!\n", sk->get_key());
      } else {
        printf("Pub failture!\n");
      }
      
    } else if(strcmp(action, "quit") == 0) {
      printf("(%d) quit\n", sk->get_key());
      delete sk;
      break;
    } else {
      printf("error input argument\n");
      continue;
    }
   
  }
 
}
 
 
 
int main(int argc, char *argv[]) {
  shm_mm_wrapper_init(512);
  int key;
  if (argc < 3) {
    fprintf(stderr, "Usage: %s %s|%s  <key> ...\n", argv[0], "server", "client");
    return 1;
  }
 
  key = atoi(argv[2]);
 
  if (strcmp("server", argv[1]) == 0) {
   server(key);
    
  } else if (strcmp("client", argv[1]) == 0) {
    client(key);
  }  
 
 
  
  return 0;
}