File: test_sockets_send_while_connecting.c

package info (click to toggle)
emscripten 3.1.69%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 121,872 kB
  • sloc: ansic: 636,110; cpp: 425,974; javascript: 78,401; python: 58,404; sh: 49,154; pascal: 5,237; makefile: 3,365; asm: 2,415; lisp: 1,869
file content (60 lines) | stat: -rw-r--r-- 1,593 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// This test verifies that calling send() back to back right after calling
// connect() succeeds.

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <emscripten/html5.h>
#include <string.h>
#include <stdio.h>

int sock;

EM_BOOL wait_for_recv(double d, void *u) {
  // Poll read from the socket to see what we have received
  char buf[1024] = {};
  recv(sock, buf, sizeof(buf)-1, 0);
  if (strlen(buf) > 0) {
    printf("%s\n", buf);
    if (!strcmp(buf, "Hello")) {
      printf("Got hello, test finished.\n");
#ifdef REPORT_RESULT
      REPORT_RESULT(0);
#endif
    }
  }
  return EM_TRUE;
}

int main() {
  // Connect socket to a WebSocket echo server
  struct sockaddr_in addr = {
    .sin_family = AF_INET,
    .sin_port = htons(8089)
  };
  inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock < 0) {
    printf("socket() failed to error %d\n", sock);
    return sock;    
  }

  // Connect to echo server.
  int error = connect(sock, (struct sockaddr*)&addr, sizeof(addr));
  if (error) {
    printf("connect() failed to error %d\n", error);
    return error;
  }

  // Immediately send a message back-to-back from connecting to the socket
  const char *msg = "Hello";
  ssize_t bytes = send(sock, msg, strlen(msg), 0);
  if (bytes != strlen(msg)) {
    printf("send() failed to send %d bytes. Return value: %d\n", (int)strlen(msg), (int)bytes);
    return bytes;
  }

  // Asynchronously wait until we get the message echoed back
  emscripten_set_timeout_loop(wait_for_recv, 0, 0);
  return 0;
}