server_mainloop.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 <signal.h>
  6. #ifdef _WIN32
  7. # include <winsock2.h>
  8. #else
  9. # include <sys/select.h>
  10. #endif
  11. #ifdef UA_NO_AMALGAMATION
  12. # include "ua_types.h"
  13. # include "ua_server.h"
  14. # include "ua_config_standard.h"
  15. # include "networklayer_tcp.h"
  16. #else
  17. # include "open62541.h"
  18. #endif
  19. UA_Boolean running = true;
  20. UA_Logger logger = Logger_Stdout;
  21. static void stopHandler(int sign) {
  22. UA_LOG_INFO(logger, UA_LOGCATEGORY_SERVER, "received ctrl-c");
  23. running = false;
  24. }
  25. /* In this example, we integrate the server into an external "mainloop". This
  26. can be for example the event-loop used in GUI toolkits, such as Qt or GTK. */
  27. int main(int argc, char** argv) {
  28. signal(SIGINT, stopHandler); /* catches ctrl-c */
  29. UA_ServerConfig config = UA_ServerConfig_standard;
  30. UA_ServerNetworkLayer nl = UA_ServerNetworkLayerTCP(UA_ConnectionConfig_standard, 16664);
  31. config.networkLayers = &nl;
  32. config.networkLayersSize = 1;
  33. UA_Server *server = UA_Server_new(config);
  34. UA_StatusCode retval = UA_Server_run_startup(server);
  35. if(retval != UA_STATUSCODE_GOOD)
  36. goto cleanup;
  37. /* Should the server networklayer block (with a timeout) until a message
  38. arrives or should it return immediately? */
  39. UA_Boolean waitInternal = false;
  40. while(running) {
  41. /* timeout is the maximum possible delay (in millisec) until the next
  42. _iterate call. Otherwise, the server might miss an internal timeout
  43. or cannot react to messages with the promised responsiveness. */
  44. UA_UInt16 timeout = UA_Server_run_iterate(server, waitInternal);
  45. /* Now we can use the max timeout to do something else. In this case, we
  46. just sleep. (select is used as a platform-independent sleep
  47. function.) */
  48. struct timeval tv;
  49. tv.tv_sec = 0;
  50. tv.tv_usec = timeout * 1000;
  51. select(0, NULL, NULL, NULL, &tv);
  52. }
  53. retval = UA_Server_run_shutdown(server);
  54. cleanup:
  55. UA_Server_delete(server);
  56. nl.deleteMembers(&nl);
  57. return (int)retval;
  58. }