Browse Source

Fixed closed callback

Paul-Louis Ageneau 5 years ago
parent
commit
9425641f54
3 changed files with 17 additions and 7 deletions
  1. 12 4
      src/websocket.cpp
  2. 1 1
      src/wstransport.cpp
  3. 4 2
      test/websocket.cpp

+ 12 - 4
src/websocket.cpp

@@ -75,9 +75,9 @@ void WebSocket::open(const string &url) {
 }
 
 void WebSocket::close() {
-	PLOG_VERBOSE << "Closing WebSocket";
 	auto state = mState.load();
 	if (state == State::Connecting || state == State::Open) {
+		PLOG_VERBOSE << "Closing WebSocket";
 		changeState(State::Closing);
 		if (auto transport = std::atomic_load(&mWsTransport))
 			transport->close();
@@ -87,8 +87,10 @@ void WebSocket::close() {
 }
 
 void WebSocket::remoteClose() {
-	close();
-	closeTransports();
+	if (mState.load() != State::Closed) {
+		close();
+		closeTransports();
+	}
 }
 
 bool WebSocket::send(const std::variant<binary, string> &data) {
@@ -287,7 +289,13 @@ std::shared_ptr<WsTransport> WebSocket::initWsTransport() {
 void WebSocket::closeTransports() {
 	PLOG_VERBOSE << "Closing transports";
 
-	changeState(State::Closed);
+	if (mState.load() != State::Closed) {
+		changeState(State::Closed);
+		triggerClosed();
+	}
+
+	// Reset callbacks now that state is changed
+	resetCallbacks();
 
 	// Pass the references to a thread, allowing to terminate a transport from its own thread
 	auto ws = std::atomic_exchange(&mWsTransport, decltype(mWsTransport)(nullptr));

+ 1 - 1
src/wstransport.cpp

@@ -147,7 +147,7 @@ void WsTransport::close() {
 	if (state() == State::Connected) {
 		sendFrame({CLOSE, NULL, 0, true, true});
 		PLOG_INFO << "WebSocket closing";
-		changeState(State::Completed);
+		changeState(State::Disconnected);
 	}
 }
 

+ 4 - 2
test/websocket.cpp

@@ -32,9 +32,9 @@ using namespace std;
 template <class T> weak_ptr<T> make_weak_ptr(shared_ptr<T> ptr) { return ptr; }
 
 void test_websocket() {
-	InitLogger(LogLevel::Verbose);
+	InitLogger(LogLevel::Debug);
 
-	const string myMessage = "Hello world";
+	const string myMessage = "Hello world from libdatachannel";
 
 	auto ws = std::make_shared<WebSocket>();
 
@@ -46,6 +46,8 @@ void test_websocket() {
 		ws->send(myMessage);
 	});
 
+	ws->onClosed([]() { cout << "WebSocket: Closed" << endl; });
+
 	std::atomic<bool> received = false;
 	ws->onMessage([&received, &myMessage](const variant<binary, string> &message) {
 		if (holds_alternative<string>(message)) {