connection.c 2.1 KB

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