33#include <emscripten/websocket.h>
44#include <assert.h>
55
6- // This test performs that same server communications using two different
6+ // This test performs the same server communications using two different
77// sockets. This verifies that multiple sockets are supported simultaneously.
8+ // Depending on whether TEST_EMSCRIPTEN_WEBSOCKET_DEINITIALIZE is defined,
9+ // cleanup is either performed using emscripten_websocket_deinitialize() or
10+ // emscripten_websocket_close() and emscripten_websocket_delete().
811EMSCRIPTEN_WEBSOCKET_T sock1 ;
912EMSCRIPTEN_WEBSOCKET_T sock2 ;
1013
@@ -44,6 +47,7 @@ bool WebSocketError(int eventType, const EmscriptenWebSocketErrorEvent *e, void
4447bool WebSocketMessage (int eventType , const EmscriptenWebSocketMessageEvent * e , void * userData ) {
4548 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 );
4649 static int text_received = 0 ;
50+ static int binary_received = 0 ;
4751 assert (e -> socket == sock1 || e -> socket == sock2 );
4852 if (e -> isText ) {
4953 printf ("text data: \"%s\"\n" , e -> data );
@@ -54,13 +58,39 @@ bool WebSocketMessage(int eventType, const EmscriptenWebSocketMessageEvent *e, v
5458
5559 // We expect to receive the text message before the binary one
5660 assert (text_received );
61+ binary_received ++ ;
5762 printf ("binary data:" );
5863 for (int i = 0 ; i < e -> numBytes ; ++ i ) {
5964 printf (" %02X" , e -> data [i ]);
6065 assert (e -> data [i ] == i );
6166 }
6267 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
6384 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+
6494 return 0 ;
6595}
6696
0 commit comments