eidheim / Simple-WebSocket-Server

A very simple, fast, multithreaded, platform independent WebSocket (WS) and WebSocket Secure (WSS) server and client library implemented using C++11, Boost.Asio and OpenSSL. Created to be an easy way to make WebSocket endpoints in C++.
MIT License
800 stars 278 forks source link

how to initiate send message from client #94

Open 1355700334 opened 6 years ago

1355700334 commented 6 years ago

it seems client can only send message within a callback function like on_open(), because it requires "shared_ptr" 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_ptr be made into a variable in the client class? or else how to do that? thanks.

eidheim commented 6 years ago

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.

koallen commented 6 years ago

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.

eidheim commented 6 years ago

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.