Simple-WebSocket-Server icon indicating copy to clipboard operation
Simple-WebSocket-Server copied to clipboard

how to initiate send message from client

Open 1355700334 opened this issue 7 years ago • 3 comments

it seems client can only send message within a callback function like on_open(), because it requires "shared_ptrWssClient::Connection" from the on_open input parameter to make the "connection->send(send_stream);" action. But if in my application, the client side sometimes needs to initiate the message, something like this function:

void sendMsg(msg) {}

can the shared_ptrWssClient::Connection be made into a variable in the client class? or else how to do that? thanks.

1355700334 avatar Jan 19 '18 08:01 1355700334

You can store the connection shared_ptr that you receive from the on_open handler, and use this shared_ptr to send messages outside of the handlers.

eidheim avatar Jan 19 '18 10:01 eidheim

I'm trying the same thing. It seems that once I call client.start(), the thread starts listening to events and I cannot do anything on this thread. I have to start another thread to initiate send from the client (after getting the Connection object).

Is this expected behavior? I'm new to WebSocket, but in traditional socket programming once we connect we can keep operating in the thread.

koallen avatar May 16 '18 11:05 koallen

Yes, this library is asynchronous, so this is expected behaviour. When you call client.start() the handlers (the on_message lambda for instance) are run in this thread.

eidheim avatar May 18 '18 09:05 eidheim