server_mainloop.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * This work is licensed under a Creative Commons CCZero 1.0 Universal License.
  3. * See http://creativecommons.org/publicdomain/zero/1.0/ for more information.
  4. */
  5. #include <ua_server.h>
  6. #include <ua_config_default.h>
  7. #include <ua_log_stdout.h>
  8. #include <signal.h>
  9. UA_Boolean running = true;
  10. static void stopHandler(int sign) {
  11. UA_LOG_INFO(UA_Log_Stdout, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  12. running = false;
  13. }
  14. /* In this example, we integrate the server into an external "mainloop". This
  15. can be for example the event-loop used in GUI toolkits, such as Qt or GTK. */
  16. int main(int argc, char** argv) {
  17. signal(SIGINT, stopHandler);
  18. signal(SIGTERM, stopHandler);
  19. UA_ServerConfig *config = UA_ServerConfig_new_default();
  20. UA_Server *server = UA_Server_new(config);
  21. /* Should the server networklayer block (with a timeout) until a message
  22. arrives or should it return immediately? */
  23. UA_Boolean waitInternal = false;
  24. UA_StatusCode retval = UA_Server_run_startup(server);
  25. if(retval != UA_STATUSCODE_GOOD)
  26. goto cleanup;
  27. while(running) {
  28. /* timeout is the maximum possible delay (in millisec) until the next
  29. _iterate call. Otherwise, the server might miss an internal timeout
  30. or cannot react to messages with the promised responsiveness. */
  31. /* If multicast discovery server is enabled, the timeout does not not consider new input data (requests) on the mDNS socket.
  32. * It will be handled on the next call, which may be too late for requesting clients.
  33. * if needed, the select with timeout on the multicast socket server->mdnsSocket (see example in mdnsd library)
  34. */
  35. UA_UInt16 timeout = UA_Server_run_iterate(server, waitInternal);
  36. /* Now we can use the max timeout to do something else. In this case, we
  37. just sleep. (select is used as a platform-independent sleep
  38. function.) */
  39. struct timeval tv;
  40. tv.tv_sec = 0;
  41. tv.tv_usec = timeout * 1000;
  42. select(0, NULL, NULL, NULL, &tv);
  43. }
  44. retval = UA_Server_run_shutdown(server);
  45. cleanup:
  46. UA_Server_delete(server);
  47. UA_ServerConfig_delete(config);
  48. return (int)retval;
  49. }