Debian Codegraph @

protolib/examples/pipeExample.cpp

raw
1
2 #include "protokit.h"
3 #include <stdio.h> // for stderr output as needed
4 #include <stdlib.h> // for atoi()
5
6 // 1) Uncomment this for example using Protolib async i/o
7 #define ASYNC_IO_EXAMPLE
8
9 // 2) Uncomment _one_ of these ProtoPipe "types" for demonstration
10 #define PIPE_TYPE ProtoPipe::MESSAGE
11 //#define PIPE_TYPE ProtoPipe::STREAM
12
13 #ifdef ASYNC_IO_EXAMPLE
14 /**
15 * @class PipeExample
16 *
17 * @brief This example program illustrates/tests the use of the ProtoPipe class
18 * for local domain interprocess communications
19 */
20 class PipeExample : public ProtoApp
21 {
22 public:
23 PipeExample();
24 ~PipeExample();
25
26 // Overrides from ProtoApp or NsProtoSimAgent base
27 bool OnStartup(int argc, const char*const* argv);
28 bool ProcessCommands(int argc, const char*const* argv);
29 void OnShutdown();
30
31 bool OnCommand(const char* cmd, const char* val);
32
33 private:
34 enum CmdType {CMD_INVALID, CMD_ARG, CMD_NOARG};
35 static CmdType GetCmdType(const char* string);
36 static const char* const CMD_LIST[];
37 void Usage();
38
39 bool OnSendTimeout(ProtoTimer& theTimer);
40 void OnServerEvent(ProtoSocket& theSocket,
41 ProtoSocket::Event theEvent);
42 void OnClientEvent(ProtoSocket& theSocket,
43 ProtoSocket::Event theEvent);
44
45 ProtoTimer send_timer;
46 ProtoPipe server_pipe;
47 ProtoPipe client_pipe;
48 char* msg_buffer;
49 unsigned int msg_len;
50 unsigned int msg_index;
51 int msg_repeat;
52 int msg_repeat_count;
53
54
55 }; // end class PipeExample
56
57 // Instantiate our application instance
58 PROTO_INSTANTIATE_APP(PipeExample)
59
60 PipeExample::PipeExample()
61 : server_pipe(PIPE_TYPE), client_pipe(PIPE_TYPE),
62 msg_buffer(NULL), msg_len(0), msg_index(0),
63 msg_repeat(0), msg_repeat_count(0)
64 {
65 send_timer.SetListener(this, &PipeExample::OnSendTimeout);
66 send_timer.SetInterval(1.0);
67 send_timer.SetRepeat(-1);
68 server_pipe.SetNotifier(&GetSocketNotifier());
69 server_pipe.SetListener(this, &PipeExample::OnServerEvent);
70 client_pipe.SetNotifier(&GetSocketNotifier());
71 client_pipe.SetListener(this, &PipeExample::OnClientEvent);
72 }
73
74 PipeExample::~PipeExample()
75 {
76 if (NULL != msg_buffer)
77 {
78 delete[] msg_buffer;
79 msg_buffer = NULL;
80 }
81 }
82
83 const char* const PipeExample::CMD_LIST[] =
84 {
85 "+listen", // Listen for TCP connections on <port>
86 "+connect", // TCP connect and send to destination host/port
87 "+repeat", // repeat message multiple times
88 "+send", // Send UDP packets to destination host/port
89 NULL
90 };
91
92 void PipeExample::Usage()
93 {
94 fprintf(stderr, "pipeExample [listen <serverName>][connect <serverName>]\n"
95 " [send <message>][repeat <repeatCount>]\n");
96 } // end PipeExample::Usage()
97
98 bool PipeExample::OnStartup(int argc, const char*const* argv)
99 {
100 if (argc < 2)
101 {
102 Usage();
103 return false;
104 }
105 if (!ProcessCommands(argc, argv))
106 {
107 PLOG(PL_ERROR, "PipeExample::OnStartup() error processing command line\n");
108 Usage();
109 return false;
110 }
111 return true;
112 } // end PipeExample::OnStartup()
113
114 void PipeExample::OnShutdown()
115 {
116 if (send_timer.IsActive()) send_timer.Deactivate();
117 if (server_pipe.IsOpen()) server_pipe.Close();
118 if (client_pipe.IsOpen()) client_pipe.Close();
119 PLOG(PL_ERROR, "pipeExample: Done.\n");
120 } // end PipeExample::OnShutdown()
121
122 bool PipeExample::OnCommand(const char* cmd, const char* val)
123 {
124 CmdType type = GetCmdType(cmd);
125 ASSERT(CMD_INVALID != type);
126 unsigned int len = strlen(cmd);
127 if ((CMD_ARG == type) && !val)
128 {
129 PLOG(PL_ERROR, "pipeExample::ProcessCommand(%s) missing argument\n", cmd);
130 return false;
131 }
132 else if (!strncmp("listen", cmd, len))
133 {
134 if (server_pipe.IsOpen()) server_pipe.Close();
135 if (!server_pipe.Listen(val))
136 {
137 PLOG(PL_ERROR, "PipeExample::OnCommand() server_pipe.Listen() error\n");
138 return false;
139 }
140 TRACE("pipeExample: server \"%s\" listening ...\n", val);
141 }
142 else if (!strncmp("connect", cmd, len))
143 {
144 if (client_pipe.IsOpen()) client_pipe.Close();
145 if (!client_pipe.Connect(val))
146 {
147 PLOG(PL_ERROR, "PipeExample::OnCommand() client_pipe.Connect() error: %s\n",
148 GetErrorString());
149 return false;
150 }
151 }
152 else if (!strncmp("repeat", cmd, len))
153 {
154 msg_repeat = atoi(val);
155 }
156 else if (!strncmp("send", cmd, len))
157 {
158 if (msg_buffer) delete[] msg_buffer;
159 msg_len = strlen(val) + 1;
160 if (!(msg_buffer = new char[msg_len]))
161 {
162 PLOG(PL_ERROR, "pipeExample: new msg_buffer error: %s\n", GetErrorString());
163 msg_len = 0;
164 return false;
165 }
166 memcpy(msg_buffer, val, msg_len);
167 msg_index = 0;
168 msg_repeat_count = msg_repeat;
169 if (ProtoPipe::MESSAGE == client_pipe.GetType())
170 {
171 if (send_timer.IsActive()) send_timer.Deactivate();
172 if (msg_repeat_count) ActivateTimer(send_timer);
173 OnSendTimeout(send_timer); // go ahead and send msg immediately
174 }
175 else
176 {
177 if (!client_pipe.StartOutputNotification())
178 {
179 PLOG(PL_ERROR, "PipeExample::OnCommand() StartOutputNotification() error\n");
180 return false;
181 }
182 }
183 }
184 else
185 {
186 PLOG(PL_ERROR, "PipeExample::OnCommand() unknown command error?\n");
187 return false;
188 }
189 return true;
190 } // end PipeExample::OnCommand()
191
192 bool PipeExample::OnSendTimeout(ProtoTimer& /*theTimer*/)
193 {
194 if (msg_buffer && client_pipe.IsOpen())
195 {
196 unsigned int len = msg_len - msg_index;
197 if (client_pipe.Send(msg_buffer+msg_index, len))
198 {
199 msg_index += len;
200 if (msg_index >= msg_len)
201 {
202 msg_index = 0;
203 if (0 == msg_repeat_count)
204 {
205 if (send_timer.IsActive()) send_timer.Deactivate();
206 client_pipe.Close();
207 return false;
208 }
209 if (msg_repeat_count > 0) msg_repeat_count--;
210 }
211 TRACE("pipeExample: client sent %d bytes ...\n", len);
212 }
213 else
214 {
215 PLOG(PL_ERROR, "PipeExample::OnSendTimeout() client_pipe.Send() error\n");
216 client_pipe.Close();
217 }
218 }
219 return true;
220 } // end PipeExample::OnSendTimeout()
221
222 void PipeExample::OnServerEvent(ProtoSocket& /*theSocket*/,
223 ProtoSocket::Event theEvent)
224 {
225 switch (theEvent)
226 {
227 case ProtoSocket::RECV:
228 {
229 TRACE("pipeExample: server RECV event ..\n");
230 char buffer[8192];
231 unsigned int len = 8191;
232 if (server_pipe.Recv(buffer, len))
233 {
234 if (len)
235 PLOG(PL_ERROR, "pipeExample: recvd \"%s\"\n", buffer);
236 }
237 else
238 {
239 PLOG(PL_ERROR, "PipeExample::OnServerEvent() server_pipe.Recv() error\n");
240 }
241 break;
242 }
243 case ProtoSocket::SEND:
244 TRACE("pipeExample: server SEND event ..\n");
245 break;
246 case ProtoSocket::ACCEPT:
247 TRACE("pipeExample: server ACCEPT event ..\n");
248 if (!server_pipe.Accept())
249 PLOG(PL_ERROR, "PipeExample::OnServerEvent() server_pipe.Accept() error\n");
250 break;
251 case ProtoSocket::DISCONNECT:
252 TRACE("pipeExample: server DISCONNECT event ..\n");
253 char pipeName[PATH_MAX];
254 strncpy(pipeName, server_pipe.GetName(), PATH_MAX);
255 server_pipe.Close();
256 if (!server_pipe.Listen(pipeName))
257 PLOG(PL_ERROR, "pipeExample: error restarting server pipe ...\n");
258 break;
259 default:
260 TRACE("PipeExample::OnServerEvent(%d) unhandled event type\n", theEvent);
261 break;
262
263 } // end switch(theEvent)
264 } // end PipeExample::OnServerEvent()
265
266
267 void PipeExample::OnClientEvent(ProtoSocket& /*theSocket*/,
268 ProtoSocket::Event theEvent)
269 {
270 switch (theEvent)
271 {
272 case ProtoSocket::CONNECT:
273 PLOG(PL_ERROR, "pipeExample: clientconnected to server.\n");
274 break;
275 case ProtoSocket::RECV:
276 {
277 TRACE("pipeExample: client RECV event ...\n");
278 break;
279 }
280 case ProtoSocket::SEND:
281 TRACE("pipeExample: client SEND event ...\n");
282 OnSendTimeout(send_timer);
283 break;
284 case ProtoSocket::DISCONNECT:
285 TRACE("pipeExample: client DISCONNECT event ...\n");
286 client_pipe.Close();
287 break;
288 default:
289 TRACE("pipeExample::OnClientEvent(%d) unhandled event type\n", theEvent);
290 break;
291
292 } // end switch(theEvent)
293 } // end PipeExample::OnClientEvent()
294
295
296 PipeExample::CmdType PipeExample::GetCmdType(const char* cmd)
297 {
298 if (!cmd) return CMD_INVALID;
299 unsigned int len = strlen(cmd);
300 bool matched = false;
301 CmdType type = CMD_INVALID;
302 const char* const* nextCmd = CMD_LIST;
303 while (*nextCmd)
304 {
305 if (!strncmp(cmd, *nextCmd+1, len))
306 {
307 if (matched)
308 {
309 // ambiguous command (command should match only once)
310 return CMD_INVALID;
311 }
312 else
313 {
314 matched = true;
315 if ('+' == *nextCmd[0])
316 type = CMD_ARG;
317 else
318 type = CMD_NOARG;
319 }
320 }
321 nextCmd++;
322 }
323 return type;
324 } // end PipeExample::GetCmdType()
325
326 bool PipeExample::ProcessCommands(int argc, const char*const* argv)
327 {
328 // Dispatch command-line commands to our OnCommand() method
329 int i = 1;
330 while ( i < argc)
331 {
332 // Is it a class PipeExample command?
333 switch (GetCmdType(argv[i]))
334 {
335 case CMD_INVALID:
336 {
337 #ifndef SIMULATE
338 PLOG(PL_ERROR, "pipeExample::ProcessCommands() Invalid command:%s\n",
339 argv[i]);
340 #endif // SIMULATE
341 return false;
342 }
343 case CMD_NOARG:
344 if (!OnCommand(argv[i], NULL))
345 {
346 PLOG(PL_ERROR, "pipeExample::ProcessCommands() ProcessCommand(%s) error\n",
347 argv[i]);
348 return false;
349 }
350 i++;
351 break;
352 case CMD_ARG:
353 if (!OnCommand(argv[i], argv[i+1]))
354 {
355 PLOG(PL_ERROR, "pipeExample::ProcessCommands() ProcessCommand(%s, %s) error\n",
356 argv[i], argv[i+1]);
357 return false;
358 }
359 i += 2;
360 break;
361 }
362 }
363 return true;
364 } // end PipeExample::ProcessCommands()
365
366 #else
367
368 int main(int argc, char* argv[])
369 {
370 if (argc > 1)
371 {
372 // Connect to server and send command line args
373 ProtoPipe client(PIPE_TYPE);
374 if (!client.Connect("protoDaemon"))
375 {
376 PLOG(PL_ERROR, "pipeExample: error connecting to server\n");
377 return -1;
378 }
379 for (int i = 1; i < argc; i++)
380 {
381 // Send args including '\0' termination char
382 unsigned int len = strlen(argv[i]) + 1;
383 if (!client.Send(argv[i], len))
384 {
385 PLOG(PL_ERROR, "pipeExample: error sending to server\n");
386 return -1;
387 }
388 }
389 client.Close();
390 }
391 else
392 {
393 // No args, so just open up a "protoDaemon" server
394 while(1)
395 {
396 ProtoPipe server(PIPE_TYPE);
397 ProtoPipe acceptPipe(PIPE_TYPE);
398 ProtoPipe& recvPipe = (ProtoPipe::STREAM == server.GetType()) ? acceptPipe : server;
399 PLOG(PL_ERROR, "pipeExample: server listening ...\n");
400 if (!server.Listen("protoDaemon"))
401 {
402 PLOG(PL_ERROR, "pipeExample: error opening server socket\n");
403 return -1;
404 }
405 if (ProtoPipe::STREAM == server.GetType())
406 {
407 // "STREAM" ProtoPipes are connection-oriented
408 // Note that the argument to Accept() is optional if the
409 // application only wants to have one connection at a time
410 if (!server.Accept(&acceptPipe))
411 {
412 PLOG(PL_ERROR, "pipeExample: error accepting connection\n");
413 server.Close();
414 return -1;
415 }
416 }
417 char buffer[1024];
418 unsigned int len = 1024;
419 while (recvPipe.Recv(buffer, len))
420 {
421 if (0 != len)
422 PLOG(PL_ERROR, "pipeExample: server recv'd \"%s\" ...\n", buffer);
423 else
424 break;
425 len = 1024;
426 }
427 server.Close();
428 recvPipe.Close();
429 }
430 }
431 return 0;
432 }
433
434 #endif // if/else ASYNC_IO_EXAMPLE