| 45 | } |
| 46 | |
| 47 | bool WebSocketMessage(int eventType, const EmscriptenWebSocketMessageEvent *e, void *userData) { |
| 48 | printf("message(socket=%d, eventType=%d, userData=%p data=%p, numBytes=%d, isText=%d)\n", e->socket, eventType, userData, e->data, e->numBytes, e->isText); |
| 49 | static int text_received = 0; |
| 50 | static int binary_received = 0; |
| 51 | assert(e->socket == sock1 || e->socket == sock2); |
| 52 | if (e->isText) { |
| 53 | printf("text data: \"%s\"\n", e->data); |
| 54 | assert(strcmp((const char*)e->data, "hello on the other side") == 0); |
| 55 | text_received++; |
| 56 | return 0; |
| 57 | } |
| 58 | |
| 59 | // We expect to receive the text message before the binary one |
| 60 | assert(text_received); |
| 61 | binary_received++; |
| 62 | printf("binary data:"); |
| 63 | for (int i = 0; i < e->numBytes; ++i) { |
| 64 | printf(" %02X", e->data[i]); |
| 65 | assert(e->data[i] == i); |
| 66 | } |
| 67 | printf("\n"); |
| 68 | |
| 69 | #ifdef TEST_EMSCRIPTEN_WEBSOCKET_DEINITIALIZE |
| 70 | if (binary_received == 2) { |
| 71 | // We successfully received binary data from both websockets. |
| 72 | // We are done. We can deinitialize and exit. |
| 73 | emscripten_websocket_deinitialize(); |
| 74 | // All websocket handles are invalidated. |
| 75 | // It is no longer possible to query their state. |
| 76 | unsigned short ready_state; |
| 77 | EMSCRIPTEN_RESULT result = emscripten_websocket_get_ready_state(e->socket, &ready_state); |
| 78 | assert(result == EMSCRIPTEN_RESULT_INVALID_TARGET); |
| 79 | (void)ready_state; |
| 80 | sock1 = sock2 = 0; |
| 81 | emscripten_force_exit(0); |
| 82 | } |
| 83 | #else |
| 84 | emscripten_websocket_close(e->socket, 0, 0); |
| 85 | // The WebSocket is being closed, but its handle is still valid. |
| 86 | // It should therefore still be possible to query its state. |
| 87 | unsigned short ready_state; |
| 88 | EMSCRIPTEN_RESULT result = emscripten_websocket_get_ready_state(e->socket, &ready_state); |
| 89 | assert(result == EMSCRIPTEN_RESULT_SUCCESS); |
| 90 | // https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState |
| 91 | assert(ready_state == 2); // 2 = CLOSING |
| 92 | #endif // TEST_EMSCRIPTEN_WEBSOCKET_DEINITIALIZE |
| 93 | |
| 94 | return 0; |
| 95 | } |
| 96 | |
| 97 | EMSCRIPTEN_WEBSOCKET_T create_socket() { |
| 98 | EmscriptenWebSocketCreateAttributes attr; |