connection.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "wasm_app.h"
  6. #include "wa-inc/connection.h"
  7. #include "wa-inc/timer_wasm_app.h"
  8. #include "wa-inc/request.h"
  9. /* User global variable */
  10. static int num = 0;
  11. static user_timer_t g_timer;
  12. static connection_t *g_conn = NULL;
  13. void on_data1(connection_t *conn,
  14. conn_event_type_t type,
  15. const char *data,
  16. uint32 len,
  17. void *user_data)
  18. {
  19. if (type == CONN_EVENT_TYPE_DATA) {
  20. char message[64] = {0};
  21. memcpy(message, data, len);
  22. printf("Client got a message from server -> %s\n", message);
  23. } else if (type == CONN_EVENT_TYPE_DISCONNECT) {
  24. printf("connection is close by server!\n");
  25. } else {
  26. printf("error: got unknown event type!!!\n");
  27. }
  28. }
  29. /* Timer callback */
  30. void timer1_update(user_timer_t timer)
  31. {
  32. char message[64] = {0};
  33. /* Reply to server */
  34. snprintf(message, sizeof(message), "Hello %d", num++);
  35. api_send_on_connection(g_conn, message, strlen(message));
  36. }
  37. void my_close_handler(request_t * request)
  38. {
  39. response_t response[1];
  40. if (g_conn != NULL) {
  41. api_timer_cancel(g_timer);
  42. api_close_connection(g_conn);
  43. }
  44. make_response_for_request(request, response);
  45. set_response(response, DELETED_2_02, 0, NULL, 0);
  46. api_response_send(response);
  47. }
  48. void on_init()
  49. {
  50. user_timer_t timer;
  51. attr_container_t *args;
  52. char *str = "this is client!";
  53. api_register_resource_handler("/close", my_close_handler);
  54. args = attr_container_create("");
  55. attr_container_set_string(&args, "address", "127.0.0.1");
  56. attr_container_set_uint16(&args, "port", 7777);
  57. g_conn = api_open_connection("TCP", args, on_data1, NULL);
  58. if (g_conn == NULL) {
  59. printf("connect to server fail!\n");
  60. return;
  61. }
  62. printf("connect to server success! handle: %p\n", g_conn);
  63. /* set up a timer */
  64. timer = api_timer_create(1000, true, false, timer1_update);
  65. api_timer_restart(timer, 1000);
  66. }
  67. void on_destroy()
  68. {
  69. /* real destroy work including killing timer and closing sensor is
  70. accomplished in wasm app library version of on_destroy() */
  71. }