connection.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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
  14. on_data1(connection_t *conn, conn_event_type_t type, const char *data,
  15. uint32 len, void *user_data)
  16. {
  17. if (type == CONN_EVENT_TYPE_DATA) {
  18. char message[64] = { 0 };
  19. memcpy(message, data, len);
  20. printf("Client got a message from server -> %s\n", message);
  21. }
  22. else if (type == CONN_EVENT_TYPE_DISCONNECT) {
  23. printf("connection is close by server!\n");
  24. }
  25. else {
  26. printf("error: got unknown event type!!!\n");
  27. }
  28. }
  29. /* Timer callback */
  30. void
  31. timer1_update(user_timer_t timer)
  32. {
  33. char message[64] = { 0 };
  34. /* Reply to server */
  35. snprintf(message, sizeof(message), "Hello %d", num++);
  36. api_send_on_connection(g_conn, message, strlen(message));
  37. }
  38. void
  39. my_close_handler(request_t *request)
  40. {
  41. response_t response[1];
  42. if (g_conn != NULL) {
  43. api_timer_cancel(g_timer);
  44. api_close_connection(g_conn);
  45. }
  46. make_response_for_request(request, response);
  47. set_response(response, DELETED_2_02, 0, NULL, 0);
  48. api_response_send(response);
  49. }
  50. void
  51. on_init()
  52. {
  53. user_timer_t timer;
  54. attr_container_t *args;
  55. char *str = "this is client!";
  56. api_register_resource_handler("/close", my_close_handler);
  57. args = attr_container_create("");
  58. attr_container_set_string(&args, "address", "127.0.0.1");
  59. attr_container_set_uint16(&args, "port", 7777);
  60. g_conn = api_open_connection("TCP", args, on_data1, NULL);
  61. if (g_conn == NULL) {
  62. printf("connect to server fail!\n");
  63. return;
  64. }
  65. printf("connect to server success! handle: %p\n", g_conn);
  66. /* set up a timer */
  67. timer = api_timer_create(1000, true, false, timer1_update);
  68. api_timer_restart(timer, 1000);
  69. }
  70. void
  71. on_destroy()
  72. {
  73. /* real destroy work including killing timer and closing sensor is
  74. accomplished in wasm app library version of on_destroy() */
  75. }