server_mainloop.c 2.1 KB

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